flyspace-cli 0.1.59 → 0.1.61

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -2,58 +2,35 @@
2
2
  import { createRequire as __flyspaceCreateRequire } from 'node:module';
3
3
  const require = __flyspaceCreateRequire(import.meta.url);
4
4
  import {
5
- AGENT_AUTHOR,
6
- DEFAULT_AUTO_CONTINUE_LIMIT,
7
- SUPPORT_BOT_AUTHOR,
8
- SYNCED_BOT_AUTHOR,
5
+ DEFAULT_CODEX_MODEL,
9
6
  SessionStore,
10
7
  __commonJS,
11
8
  __require,
12
9
  __toESM,
13
10
  databaseReachable,
14
- dmCwd,
15
- ensureAgentDmChannel,
16
- ensureChannelProvisioned,
17
11
  ensureDirs,
18
- ensureLogicalCwdDir,
19
- expandPath,
20
- findChannel,
21
- findChannelById,
22
- getChannelRegistry,
23
12
  getProfile,
24
- getProfileChannelRegistry,
25
13
  getR2Bucket,
26
14
  getR2Client,
27
15
  getSupabaseClient,
28
- hasSupabaseCredentials,
29
- isChannelAccessAllowed,
30
16
  isEffort,
31
- isHumanAuthor,
32
- isPermissionMode,
33
- onChannelRegistryChange,
17
+ loadConfig,
18
+ loadEnvFiles,
19
+ mcpStrictConfigEnabled,
34
20
  paths,
35
- postToDashboardChannel,
36
- refreshChannelRegistry,
37
- resolveAutoContinueLimit,
38
- resolveChannelPermissionMode,
39
- resolveChannelPrompt,
21
+ requestAttachmentUrl,
22
+ requestPluginSvg,
23
+ requestShouldRespond,
24
+ requireSlackBotToken,
40
25
  resolveClaudeEffort,
41
26
  resolveCodexEffort,
42
- resolveCwd,
43
- resolveEffort,
44
- resolveLogicalCwd,
45
- resolveModel,
46
- resolveOwnPersona,
47
27
  runWithProfile,
48
- setSupabaseClient,
28
+ sendAgentFailure,
49
29
  setSupabaseClientFactory,
50
- startChannelRegistryPolling,
51
30
  sweepScratchDir,
52
- syncPostToDashboard,
53
- updateChannelById,
54
31
  uploadLocalImages,
55
- warnOnBrokenChannelCwds
56
- } from "./chunk-XACRG7BO.js";
32
+ useHostDbWithoutCredentials
33
+ } from "./chunk-UZMHXV4D.js";
57
34
 
58
35
  // ../../node_modules/.pnpm/delayed-stream@1.0.0/node_modules/delayed-stream/lib/delayed_stream.js
59
36
  var require_delayed_stream = __commonJS({
@@ -9286,7 +9263,7 @@ var require_sign = __commonJS({
9286
9263
  "../../node_modules/.pnpm/math-intrinsics@1.1.0/node_modules/math-intrinsics/sign.js"(exports, module) {
9287
9264
  "use strict";
9288
9265
  var $isNaN = require_isNaN();
9289
- module.exports = function sign2(number) {
9266
+ module.exports = function sign(number) {
9290
9267
  if ($isNaN(number) || number === 0) {
9291
9268
  return number;
9292
9269
  }
@@ -9650,7 +9627,7 @@ var require_get_intrinsic = __commonJS({
9650
9627
  var min = require_min();
9651
9628
  var pow = require_pow();
9652
9629
  var round = require_round();
9653
- var sign2 = require_sign();
9630
+ var sign = require_sign();
9654
9631
  var $Function = Function;
9655
9632
  var getEvalledConstructor = function(expressionSyntax) {
9656
9633
  try {
@@ -9764,7 +9741,7 @@ var require_get_intrinsic = __commonJS({
9764
9741
  "%Math.min%": min,
9765
9742
  "%Math.pow%": pow,
9766
9743
  "%Math.round%": round,
9767
- "%Math.sign%": sign2,
9744
+ "%Math.sign%": sign,
9768
9745
  "%Reflect.getPrototypeOf%": $ReflectGPO
9769
9746
  };
9770
9747
  if (getProto) {
@@ -10954,7 +10931,7 @@ var require_supports_color = __commonJS({
10954
10931
  return 1;
10955
10932
  }
10956
10933
  if ("CI" in env) {
10957
- if (["TRAVIS", "CIRCLECI", "APPVEYOR", "GITLAB_CI", "GITHUB_ACTIONS", "BUILDKITE", "DRONE"].some((sign2) => sign2 in env) || env.CI_NAME === "codeship") {
10934
+ if (["TRAVIS", "CIRCLECI", "APPVEYOR", "GITLAB_CI", "GITHUB_ACTIONS", "BUILDKITE", "DRONE"].some((sign) => sign in env) || env.CI_NAME === "codeship") {
10958
10935
  return 1;
10959
10936
  }
10960
10937
  return min;
@@ -11618,8 +11595,8 @@ var require_follow_redirects = __commonJS({
11618
11595
  }
11619
11596
  return parsed;
11620
11597
  }
11621
- function resolveUrl(relative2, base) {
11622
- return useNativeURL ? new URL2(relative2, base) : parseUrl(url.resolve(base, relative2));
11598
+ function resolveUrl(relative3, base) {
11599
+ return useNativeURL ? new URL2(relative3, base) : parseUrl(url.resolve(base, relative3));
11623
11600
  }
11624
11601
  function validateUrl(input) {
11625
11602
  if (/^\[/.test(input.hostname) && !/^\[[:0-9a-f]+\]$/i.test(input.hostname)) {
@@ -14568,8 +14545,8 @@ var require_axios = __commonJS({
14568
14545
  };
14569
14546
  var DEFAULT_CHUNK_SIZE = 64 * 1024;
14570
14547
  var { isFunction } = utils$1;
14571
- var globalFetchAPI = (({ Request: Request2, Response: Response2 }) => ({
14572
- Request: Request2,
14548
+ var globalFetchAPI = (({ Request, Response: Response2 }) => ({
14549
+ Request,
14573
14550
  Response: Response2
14574
14551
  }))(utils$1.global);
14575
14552
  var { ReadableStream: ReadableStream$1, TextEncoder: TextEncoder$1 } = utils$1.global;
@@ -14588,18 +14565,18 @@ var require_axios = __commonJS({
14588
14565
  globalFetchAPI,
14589
14566
  env
14590
14567
  );
14591
- const { fetch: envFetch, Request: Request2, Response: Response2 } = env;
14568
+ const { fetch: envFetch, Request, Response: Response2 } = env;
14592
14569
  const isFetchSupported = envFetch ? isFunction(envFetch) : typeof fetch === "function";
14593
- const isRequestSupported = isFunction(Request2);
14570
+ const isRequestSupported = isFunction(Request);
14594
14571
  const isResponseSupported = isFunction(Response2);
14595
14572
  if (!isFetchSupported) {
14596
14573
  return false;
14597
14574
  }
14598
14575
  const isReadableStreamSupported = isFetchSupported && isFunction(ReadableStream$1);
14599
- const encodeText = isFetchSupported && (typeof TextEncoder$1 === "function" ? /* @__PURE__ */ ((encoder) => (str) => encoder.encode(str))(new TextEncoder$1()) : async (str) => new Uint8Array(await new Request2(str).arrayBuffer()));
14576
+ const encodeText = isFetchSupported && (typeof TextEncoder$1 === "function" ? /* @__PURE__ */ ((encoder) => (str) => encoder.encode(str))(new TextEncoder$1()) : async (str) => new Uint8Array(await new Request(str).arrayBuffer()));
14600
14577
  const supportsRequestStream = isRequestSupported && isReadableStreamSupported && test(() => {
14601
14578
  let duplexAccessed = false;
14602
- const hasContentType = new Request2(platform.origin, {
14579
+ const hasContentType = new Request(platform.origin, {
14603
14580
  body: new ReadableStream$1(),
14604
14581
  method: "POST",
14605
14582
  get duplex() {
@@ -14636,7 +14613,7 @@ var require_axios = __commonJS({
14636
14613
  return body.size;
14637
14614
  }
14638
14615
  if (utils$1.isSpecCompliantForm(body)) {
14639
- const _request = new Request2(platform.origin, {
14616
+ const _request = new Request(platform.origin, {
14640
14617
  method: "POST",
14641
14618
  body
14642
14619
  });
@@ -14684,7 +14661,7 @@ var require_axios = __commonJS({
14684
14661
  let requestContentLength;
14685
14662
  try {
14686
14663
  if (onUploadProgress && supportsRequestStream && method !== "get" && method !== "head" && (requestContentLength = await resolveBodyLength(headers, data)) !== 0) {
14687
- let _request = new Request2(url2, {
14664
+ let _request = new Request(url2, {
14688
14665
  method: "POST",
14689
14666
  body: data,
14690
14667
  duplex: "half"
@@ -14704,7 +14681,7 @@ var require_axios = __commonJS({
14704
14681
  if (!utils$1.isString(withCredentials)) {
14705
14682
  withCredentials = withCredentials ? "include" : "omit";
14706
14683
  }
14707
- const isCredentialsSupported = isRequestSupported && "credentials" in Request2.prototype;
14684
+ const isCredentialsSupported = isRequestSupported && "credentials" in Request.prototype;
14708
14685
  const resolvedOptions = {
14709
14686
  ...fetchOptions,
14710
14687
  signal: composedSignal,
@@ -14714,7 +14691,7 @@ var require_axios = __commonJS({
14714
14691
  duplex: "half",
14715
14692
  credentials: isCredentialsSupported ? withCredentials : void 0
14716
14693
  };
14717
- request = isRequestSupported && new Request2(url2, resolvedOptions);
14694
+ request = isRequestSupported && new Request(url2, resolvedOptions);
14718
14695
  let response = await (isRequestSupported ? _fetch(request, fetchOptions) : _fetch(url2, resolvedOptions));
14719
14696
  const isStreamResponse = supportsResponseStream && (responseType === "stream" || responseType === "response");
14720
14697
  if (supportsResponseStream && (onDownloadProgress || isStreamResponse && unsubscribe)) {
@@ -14774,8 +14751,8 @@ var require_axios = __commonJS({
14774
14751
  var seedCache = /* @__PURE__ */ new Map();
14775
14752
  var getFetch = (config) => {
14776
14753
  let env = config && config.env || {};
14777
- const { fetch: fetch2, Request: Request2, Response: Response2 } = env;
14778
- const seeds = [Request2, Response2, fetch2];
14754
+ const { fetch: fetch2, Request, Response: Response2 } = env;
14755
+ const seeds = [Request, Response2, fetch2];
14779
14756
  let len = seeds.length, i = len, seed, target, map = seedCache;
14780
14757
  while (i--) {
14781
14758
  seed = seeds[i];
@@ -17906,6 +17883,547 @@ import { mkdtempSync, rmSync as rmSync2 } from "fs";
17906
17883
  import { tmpdir } from "os";
17907
17884
  import { join as join5 } from "path";
17908
17885
 
17886
+ // ../api/src/channels.ts
17887
+ import { createHash } from "crypto";
17888
+ import { existsSync, mkdirSync, realpathSync, statSync } from "fs";
17889
+ import { homedir } from "os";
17890
+ import { isAbsolute, relative, resolve, sep } from "path";
17891
+ function isPermissionMode(value) {
17892
+ return value === "bypass" || value === "ask";
17893
+ }
17894
+ function isLogicalCwd(p) {
17895
+ return /^[a-z0-9][a-z0-9-]*\/[a-z0-9][a-z0-9-]*$/.test(p);
17896
+ }
17897
+ function logicalRoot() {
17898
+ return process.env["FLYSPACE_ROOT"] || resolve(homedir(), "Flyspace");
17899
+ }
17900
+ var workspaceRoots = /* @__PURE__ */ new Map();
17901
+ var workspacePermissionModes = /* @__PURE__ */ new Map();
17902
+ var workspaceAutoContinueLimits = /* @__PURE__ */ new Map();
17903
+ var DEFAULT_AUTO_CONTINUE_LIMIT = 3;
17904
+ async function refreshWorkspaceAutoContinueLimits() {
17905
+ const { data, error } = await getSupabaseClient().from("workspaces").select("slug, auto_continue_limit");
17906
+ if (error) return;
17907
+ workspaceAutoContinueLimits = new Map(
17908
+ (data ?? []).filter((w) => typeof w.auto_continue_limit === "number").map((w) => [w.slug, w.auto_continue_limit])
17909
+ );
17910
+ }
17911
+ function resolveAutoContinueLimit(channelId) {
17912
+ const channel = channelId ? findChannel(channelId) : void 0;
17913
+ return workspaceAutoContinueLimits.get(channel?.profile ?? getProfile()) ?? DEFAULT_AUTO_CONTINUE_LIMIT;
17914
+ }
17915
+ var workspaceOwnPersona = /* @__PURE__ */ new Set();
17916
+ async function refreshWorkspaceOwnPersona() {
17917
+ const { data, error } = await getSupabaseClient().from("workspaces").select("slug, own_persona");
17918
+ if (error) return;
17919
+ workspaceOwnPersona = new Set(
17920
+ (data ?? []).filter((w) => w.own_persona === true).map((w) => w.slug)
17921
+ );
17922
+ }
17923
+ function resolveOwnPersona(channelId) {
17924
+ const channel = channelId ? findChannel(channelId) : void 0;
17925
+ return workspaceOwnPersona.has(channel?.profile ?? getProfile());
17926
+ }
17927
+ async function refreshWorkspacePermissionModes() {
17928
+ const { data, error } = await getSupabaseClient().from("workspaces").select("slug, permission_mode");
17929
+ if (error) return;
17930
+ workspacePermissionModes = new Map(
17931
+ (data ?? []).filter((w) => isPermissionMode(w.permission_mode)).map((w) => [w.slug, w.permission_mode])
17932
+ );
17933
+ }
17934
+ async function refreshWorkspaceRoots() {
17935
+ const { data, error } = await getSupabaseClient().from("workspaces").select("slug, root_path");
17936
+ if (error) return;
17937
+ workspaceRoots = new Map(
17938
+ (data ?? []).filter((w) => w.root_path).map((w) => [w.slug, expandPath(w.root_path)])
17939
+ );
17940
+ }
17941
+ function resolveLogicalCwd(p) {
17942
+ const [slug, name] = p.split("/");
17943
+ const root = workspaceRoots.get(slug);
17944
+ return root ? resolve(root, name) : resolve(logicalRoot(), p);
17945
+ }
17946
+ function isUnderLogicalRoot(cwd) {
17947
+ return [logicalRoot(), ...workspaceRoots.values()].some((r) => cwd.startsWith(r + sep));
17948
+ }
17949
+ function toLogicalCwd(cwd) {
17950
+ const fromRoot = relative(logicalRoot(), cwd).split(sep).join("/");
17951
+ if (isLogicalCwd(fromRoot)) return fromRoot;
17952
+ for (const [slug, root] of workspaceRoots) {
17953
+ const name = relative(root, cwd);
17954
+ if (isLogicalCwd(`${slug}/${name}`)) return `${slug}/${name}`;
17955
+ }
17956
+ return cwd;
17957
+ }
17958
+ function ensureLogicalCwdDir(cwd) {
17959
+ if (!isUnderLogicalRoot(cwd) || existsSync(cwd)) return;
17960
+ mkdirSync(cwd, { recursive: true });
17961
+ }
17962
+ function expandPath(p) {
17963
+ let expanded = p;
17964
+ if (expanded === "~") {
17965
+ expanded = homedir();
17966
+ } else if (expanded.startsWith("~/")) {
17967
+ expanded = resolve(homedir(), expanded.slice(2));
17968
+ }
17969
+ return isAbsolute(expanded) ? expanded : resolve(expanded);
17970
+ }
17971
+ function normaliseMemberEmails(raw) {
17972
+ if (!Array.isArray(raw)) return [];
17973
+ const seen = /* @__PURE__ */ new Set();
17974
+ for (const v of raw) {
17975
+ if (typeof v !== "string") continue;
17976
+ const email = v.trim().toLowerCase();
17977
+ if (email) seen.add(email);
17978
+ }
17979
+ return [...seen];
17980
+ }
17981
+ function canSeeChannel(channel, viewer) {
17982
+ if (channel.visibility === "public") return true;
17983
+ if (viewer?.role === "admin" && !channel.dmKey) return true;
17984
+ const email = viewer?.email?.trim().toLowerCase();
17985
+ return !!email && channel.memberEmails.includes(email);
17986
+ }
17987
+ function rowToChannel(row) {
17988
+ return {
17989
+ id: row.id,
17990
+ name: row.name,
17991
+ categoryId: row.category_id,
17992
+ cwd: isLogicalCwd(row.cwd) ? resolveLogicalCwd(row.cwd) : expandPath(row.cwd),
17993
+ externalChannelId: row.external_channel_id,
17994
+ model: row.model,
17995
+ effort: row.effort && isEffort(row.effort) ? row.effort : null,
17996
+ prompt: row.prompt?.trim() || null,
17997
+ topicCategories: normaliseTopicCategories(row.topic_categories),
17998
+ // A uuid[] arrives as a real array; anything else (an older row read
17999
+ // through a cached client, a hand-edited value) reads as "no MCP", which
18000
+ // is the safe direction for a list that decides which credentials a run
18001
+ // can reach.
18002
+ mcpConnections: Array.isArray(row.mcp_connections) ? row.mcp_connections.filter((id) => typeof id === "string") : [],
18003
+ access: row.access ?? void 0,
18004
+ visibility: row.visibility === "public" ? "public" : "private",
18005
+ memberEmails: normaliseMemberEmails(row.member_emails),
18006
+ // The CHECK constraint (0035, extended by 0070 for 'sandbox') means the
18007
+ // stored value is always one of these three, so this narrowing is
18008
+ // unreachable in practice and exists to satisfy the type. Note it cannot
18009
+ // degrade *safely* the way `mcpConnections` does: an unreadable value here
18010
+ // would drop a channel back to the unisolated runtime, which is why the
18011
+ // constraint is the real guarantee and this is only a type-level
18012
+ // fallback.
18013
+ runtime: row.runtime === "container" ? "container" : row.runtime === "sandbox" ? "sandbox" : "host",
18014
+ // Same shape and same defensive read as `mcpConnections`: anything that
18015
+ // isn't a clean string array reads as "no mounts", which exposes less
18016
+ // rather than more.
18017
+ mounts: Array.isArray(row.mounts) ? row.mounts.filter((p) => typeof p === "string").map(expandPath) : [],
18018
+ permissionMode: isPermissionMode(row.permission_mode) ? row.permission_mode : null,
18019
+ position: row.position,
18020
+ automations: row.automations ?? void 0,
18021
+ agentName: row.agent_name,
18022
+ dmKey: row.dm_key,
18023
+ isDefault: row.is_default === true,
18024
+ profile: row.profile,
18025
+ archivedAt: row.archived_at,
18026
+ greetedAt: row.greeted_at,
18027
+ createdAt: row.created_at,
18028
+ updatedAt: row.updated_at
18029
+ };
18030
+ }
18031
+ var registry = [];
18032
+ var byId = /* @__PURE__ */ new Map();
18033
+ var byExternalId = /* @__PURE__ */ new Map();
18034
+ var changeListeners = /* @__PURE__ */ new Set();
18035
+ var lastSnapshot;
18036
+ function indexRegistry(list) {
18037
+ registry = list;
18038
+ byId = new Map(list.map((c) => [c.id, c]));
18039
+ byExternalId = new Map(
18040
+ list.filter((c) => !!c.externalChannelId).map((c) => [c.externalChannelId, c])
18041
+ );
18042
+ }
18043
+ async function refreshChannelRegistry() {
18044
+ const rootsBefore = JSON.stringify([...workspaceRoots]);
18045
+ await Promise.all([
18046
+ refreshWorkspaceRoots(),
18047
+ refreshWorkspacePermissionModes(),
18048
+ refreshWorkspaceOwnPersona(),
18049
+ refreshWorkspaceAutoContinueLimits()
18050
+ ]);
18051
+ if (JSON.stringify([...workspaceRoots]) !== rootsBefore) lastSnapshot = void 0;
18052
+ const { data, error } = await getSupabaseClient().from("channels").select("*").order("position", { ascending: true });
18053
+ if (error) {
18054
+ console.error("[channels] refreshChannelRegistry failed:", error.message);
18055
+ return;
18056
+ }
18057
+ const rows2 = data ?? [];
18058
+ const snapshot2 = JSON.stringify(
18059
+ rows2,
18060
+ (key, value) => key === "updated_at" || key === "created_at" ? void 0 : value
18061
+ );
18062
+ if (snapshot2 === lastSnapshot) return;
18063
+ lastSnapshot = snapshot2;
18064
+ indexRegistry(rows2.map(rowToChannel));
18065
+ for (const cb of changeListeners) {
18066
+ try {
18067
+ cb();
18068
+ } catch (err) {
18069
+ console.error("[channels] onChannelRegistryChange listener failed:", err);
18070
+ }
18071
+ }
18072
+ }
18073
+ function getChannelRegistry() {
18074
+ return registry;
18075
+ }
18076
+ function getProfileChannelRegistry() {
18077
+ const profile = getProfile();
18078
+ return registry.filter((ch) => ch.profile === profile);
18079
+ }
18080
+ function onChannelRegistryChange(cb) {
18081
+ changeListeners.add(cb);
18082
+ return () => changeListeners.delete(cb);
18083
+ }
18084
+ function findChannelById(id) {
18085
+ return byId.get(id);
18086
+ }
18087
+ function findChannelByExternalId(externalId) {
18088
+ return byExternalId.get(externalId);
18089
+ }
18090
+ function agentDmKey(agentName, userId) {
18091
+ return `agent:${agentName}:${userId}`;
18092
+ }
18093
+ function dmCwd(dmKey, profile = getProfile()) {
18094
+ return `${profile}/dm-${createHash("sha256").update(dmKey).digest("hex").slice(0, 24)}`;
18095
+ }
18096
+ function findChannelByAgentName(agentName, userId) {
18097
+ const dmKey = agentDmKey(agentName, userId);
18098
+ return getProfileChannelRegistry().find((c) => c.agentName === agentName && c.dmKey === dmKey);
18099
+ }
18100
+ function findChannel(ref) {
18101
+ if (!ref) return void 0;
18102
+ return byId.get(ref) ?? byExternalId.get(ref) ?? registry.find((c) => c.name === ref || c.name === ref.replace(/^#/, ""));
18103
+ }
18104
+ var DEFAULT_POLL_INTERVAL_MS = 2e4;
18105
+ var pollTimer;
18106
+ var realtimeChannel;
18107
+ function startChannelRegistryPolling(intervalMs = DEFAULT_POLL_INTERVAL_MS) {
18108
+ stopChannelRegistryPolling();
18109
+ pollTimer = setInterval(() => void refreshChannelRegistry(), intervalMs);
18110
+ try {
18111
+ realtimeChannel = getSupabaseClient().channel("channels-registry").on(
18112
+ "postgres_changes",
18113
+ { event: "*", schema: "public", table: "channels" },
18114
+ () => void refreshChannelRegistry()
18115
+ ).subscribe();
18116
+ } catch (err) {
18117
+ console.warn(
18118
+ "[channels] realtime subscribe failed \u2014 falling back to polling only:",
18119
+ err.message
18120
+ );
18121
+ }
18122
+ return stopChannelRegistryPolling;
18123
+ }
18124
+ function stopChannelRegistryPolling() {
18125
+ if (pollTimer) clearInterval(pollTimer);
18126
+ pollTimer = void 0;
18127
+ if (realtimeChannel) {
18128
+ void getSupabaseClient().removeChannel(realtimeChannel);
18129
+ realtimeChannel = void 0;
18130
+ }
18131
+ }
18132
+ function isCwdUsable(cwd) {
18133
+ try {
18134
+ return existsSync(cwd) && statSync(cwd).isDirectory();
18135
+ } catch {
18136
+ return false;
18137
+ }
18138
+ }
18139
+ function auditChannelCwds(list = registry) {
18140
+ return list.filter((ch) => ch.cwd && !isCwdUsable(ch.cwd));
18141
+ }
18142
+ function warnOnBrokenChannelCwds(list = registry) {
18143
+ const broken = auditChannelCwds(list);
18144
+ for (const ch of broken) {
18145
+ console.warn(
18146
+ `[channels] "${ch.name}" (${ch.id}): cwd "${ch.cwd}" does not exist \u2014 the agent will fall back to CLAUDE_CWD. Fix it in the channel's settings.`
18147
+ );
18148
+ }
18149
+ return broken;
18150
+ }
18151
+ function resolveChannelCwd(channelId) {
18152
+ if (!channelId) return void 0;
18153
+ const entry = findChannel(channelId);
18154
+ if (!entry?.cwd) return void 0;
18155
+ if (!isCwdUsable(entry.cwd)) {
18156
+ console.warn(
18157
+ `[channels] ${channelId}: cwd "${entry.cwd}" does not exist \u2014 falling back to CLAUDE_CWD`
18158
+ );
18159
+ return void 0;
18160
+ }
18161
+ return entry.cwd;
18162
+ }
18163
+ function isChannelAccessAllowed(channelId, userId) {
18164
+ if (!channelId) return false;
18165
+ const access = findChannel(channelId)?.access;
18166
+ if (!access) return false;
18167
+ if (typeof access === "string") {
18168
+ return access === "open" || access === "*" || access === "all";
18169
+ }
18170
+ return !!userId && access.includes(userId);
18171
+ }
18172
+ function resolveCwd(explicitCwd, channelId, fallback) {
18173
+ if (explicitCwd) return explicitCwd;
18174
+ return resolveChannelCwd(channelId) ?? fallback;
18175
+ }
18176
+ function resolveChannelModel(channelId) {
18177
+ if (!channelId) return void 0;
18178
+ return findChannel(channelId)?.model?.trim() || void 0;
18179
+ }
18180
+ function resolveChannelEffort(channelId) {
18181
+ if (!channelId) return void 0;
18182
+ return findChannel(channelId)?.effort ?? void 0;
18183
+ }
18184
+ function resolveChannelPermissionMode(channelId) {
18185
+ const channel = channelId ? findChannel(channelId) : void 0;
18186
+ return channel?.permissionMode ?? workspacePermissionModes.get(channel?.profile ?? getProfile()) ?? "bypass";
18187
+ }
18188
+ function resolveChannelPrompt(channelId) {
18189
+ if (!channelId) return void 0;
18190
+ return findChannel(channelId)?.prompt?.trim() || void 0;
18191
+ }
18192
+ function resolveModel(explicitModel, channelId, fallback) {
18193
+ if (explicitModel?.trim()) return explicitModel.trim();
18194
+ return resolveChannelModel(channelId) ?? fallback;
18195
+ }
18196
+ function resolveEffort(explicitEffort, channelId, fallback) {
18197
+ if (explicitEffort) return explicitEffort;
18198
+ return resolveChannelEffort(channelId) ?? fallback;
18199
+ }
18200
+ function normaliseTopicCategories(value) {
18201
+ if (!Array.isArray(value)) return [];
18202
+ const out = [];
18203
+ for (const v of value) {
18204
+ const t = typeof v === "string" ? v.trim() : "";
18205
+ if (t && !out.includes(t)) out.push(t);
18206
+ }
18207
+ return out;
18208
+ }
18209
+ function toRow(input) {
18210
+ const row = {};
18211
+ if (input.name !== void 0) row["name"] = input.name;
18212
+ if (input.cwd !== void 0) row["cwd"] = isLogicalCwd(input.cwd) ? input.cwd : toLogicalCwd(expandPath(input.cwd));
18213
+ if (input.categoryId !== void 0) row["category_id"] = input.categoryId;
18214
+ if (input.externalChannelId !== void 0) row["external_channel_id"] = input.externalChannelId;
18215
+ if (input.model !== void 0) row["model"] = input.model;
18216
+ if (input.effort !== void 0) row["effort"] = input.effort;
18217
+ if (input.prompt !== void 0) row["prompt"] = input.prompt?.trim() || null;
18218
+ if (input.topicCategories !== void 0) {
18219
+ const list = normaliseTopicCategories(input.topicCategories);
18220
+ row["topic_categories"] = list.length ? list : null;
18221
+ }
18222
+ if (input.access !== void 0) row["access"] = input.access;
18223
+ if (input.visibility !== void 0) row["visibility"] = input.visibility;
18224
+ if (input.memberEmails !== void 0) {
18225
+ row["member_emails"] = normaliseMemberEmails(input.memberEmails);
18226
+ }
18227
+ if (input.runtime !== void 0) row["runtime"] = input.runtime;
18228
+ if (input.mounts !== void 0) {
18229
+ row["mounts"] = input.mounts.map((p) => p.trim()).filter(Boolean).map(expandPath);
18230
+ }
18231
+ if (input.permissionMode !== void 0) row["permission_mode"] = input.permissionMode;
18232
+ if (input.position !== void 0) row["position"] = input.position;
18233
+ if (input.automations !== void 0) row["automations"] = input.automations;
18234
+ if (input.agentName !== void 0) row["agent_name"] = input.agentName;
18235
+ if (input.dmKey !== void 0) row["dm_key"] = input.dmKey;
18236
+ if (input.isDefault !== void 0) row["is_default"] = input.isDefault;
18237
+ if (input.mcpConnections !== void 0) row["mcp_connections"] = input.mcpConnections;
18238
+ if (input.archivedAt !== void 0) row["archived_at"] = input.archivedAt;
18239
+ return row;
18240
+ }
18241
+ var ChannelCwdError = class extends Error {
18242
+ constructor(message) {
18243
+ super(message);
18244
+ this.name = "ChannelCwdError";
18245
+ }
18246
+ };
18247
+ function realpathOrSelf(p) {
18248
+ try {
18249
+ return realpathSync(p);
18250
+ } catch {
18251
+ return p;
18252
+ }
18253
+ }
18254
+ async function assertCwdInWorkspace(profile, cwd) {
18255
+ if (isLogicalCwd(cwd)) {
18256
+ if (cwd.split("/")[0] !== profile) {
18257
+ throw new ChannelCwdError(`Folder "${cwd}" belongs to another workspace.`);
18258
+ }
18259
+ return cwd;
18260
+ }
18261
+ const logical = relative(logicalRoot(), cwd).split(sep).join("/");
18262
+ if (isLogicalCwd(logical)) return assertCwdInWorkspace(profile, logical);
18263
+ const { data, error } = await getSupabaseClient().from("workspaces").select("slug, root_path");
18264
+ if (error) throw new Error(error.message);
18265
+ const workspaces = data ?? [];
18266
+ const ownRoot = workspaces.find((w) => w.slug === profile)?.root_path;
18267
+ const home = ownRoot?.match(/^(\/Users\/[^/]+|\/home\/[^/]+|\/root)(?=\/|$)/)?.[1];
18268
+ const absolute = home && (cwd === "~" || cwd.startsWith("~/")) ? resolve(home, cwd.slice(2)) : expandPath(cwd);
18269
+ const path = realpathOrSelf(absolute);
18270
+ const roots = workspaces.filter((w) => w.root_path).map((w) => ({ slug: w.slug, root: realpathOrSelf(expandPath(w.root_path)) }));
18271
+ const owner = roots.filter(({ root }) => path === root || path.startsWith(root + sep)).sort((a, b) => b.root.length - a.root.length)[0];
18272
+ if (owner ? owner.slug !== profile : roots.some((r) => r.slug === profile)) {
18273
+ throw new ChannelCwdError(
18274
+ owner ? `Folder "${cwd}" belongs to the "${owner.slug}" workspace.` : `Folder "${cwd}" is outside this workspace's folder.`
18275
+ );
18276
+ }
18277
+ return absolute;
18278
+ }
18279
+ async function createChannel(input) {
18280
+ input = { ...input, cwd: await assertCwdInWorkspace(getProfile(), input.cwd) };
18281
+ const { data, error } = await getSupabaseClient().from("channels").insert({ ...toRow(input), profile: getProfile() }).select().single();
18282
+ if (error) throw new Error(error.message);
18283
+ const channel = rowToChannel(data);
18284
+ if (channel.cwd && !isLogicalCwd(input.cwd) && !isCwdUsable(channel.cwd)) {
18285
+ try {
18286
+ mkdirSync(channel.cwd, { recursive: true });
18287
+ } catch (err) {
18288
+ console.error(`[channels] failed to create cwd for "${channel.name}":`, err.message);
18289
+ }
18290
+ }
18291
+ await refreshChannelRegistry();
18292
+ return channel;
18293
+ }
18294
+ var DefaultChannelError = class extends Error {
18295
+ constructor() {
18296
+ super("The default channel must stay public and cannot be renamed or archived.");
18297
+ this.name = "DefaultChannelError";
18298
+ }
18299
+ };
18300
+ async function updateChannelById(id, patch) {
18301
+ const existing = findChannelById(id);
18302
+ if (existing?.isDefault && (patch.visibility === "private" || patch.archivedAt || patch.isDefault === false || patch.name !== void 0 && patch.name.trim() !== existing.name)) {
18303
+ throw new DefaultChannelError();
18304
+ }
18305
+ if (patch.cwd !== void 0 && existing && patch.cwd === existing.cwd) {
18306
+ const { cwd: _unchanged, ...rest } = patch;
18307
+ patch = rest;
18308
+ }
18309
+ if (patch.cwd !== void 0) {
18310
+ patch = { ...patch, cwd: await assertCwdInWorkspace(existing?.profile ?? getProfile(), patch.cwd) };
18311
+ }
18312
+ const { data, error } = await getSupabaseClient().from("channels").update({ ...toRow(patch), updated_at: (/* @__PURE__ */ new Date()).toISOString() }).eq("id", id).select().single();
18313
+ if (error) throw new Error(error.message);
18314
+ await refreshChannelRegistry();
18315
+ return rowToChannel(data);
18316
+ }
18317
+ async function markChannelGreeted(id) {
18318
+ const { data, error } = await getSupabaseClient().from("channels").update({ greeted_at: (/* @__PURE__ */ new Date()).toISOString() }).eq("id", id).is("greeted_at", null).select("id");
18319
+ if (error) throw new Error(error.message);
18320
+ await refreshChannelRegistry();
18321
+ return (data ?? []).length > 0;
18322
+ }
18323
+ async function updateChannelsMcpConnections(updates) {
18324
+ if (!updates.length) return;
18325
+ const supabase = getSupabaseClient();
18326
+ for (const update of updates) {
18327
+ const { error } = await supabase.from("channels").update({ mcp_connections: update.mcpConnections, updated_at: (/* @__PURE__ */ new Date()).toISOString() }).eq("id", update.id);
18328
+ if (error) throw new Error(`Failed to update channel ${update.id}: ${error.message}`);
18329
+ }
18330
+ await refreshChannelRegistry();
18331
+ }
18332
+ function defaultFallbackCwd() {
18333
+ return process.env["CLAUDE_CWD"] ?? process.cwd();
18334
+ }
18335
+ async function ensureChannelProvisioned(externalChannelId, opts = {}) {
18336
+ const existing = findChannelByExternalId(externalChannelId);
18337
+ if (existing) {
18338
+ if (existing.profile !== getProfile()) return null;
18339
+ if (existing.name === externalChannelId && opts.name && opts.name !== externalChannelId) {
18340
+ try {
18341
+ return await updateChannelById(existing.id, { name: opts.name });
18342
+ } catch (err) {
18343
+ console.error(`[channels] failed to heal name for ${externalChannelId}:`, err);
18344
+ return existing;
18345
+ }
18346
+ }
18347
+ return existing;
18348
+ }
18349
+ try {
18350
+ const created = await createChannel({
18351
+ name: opts.name ?? externalChannelId,
18352
+ cwd: opts.fallbackCwd ?? defaultFallbackCwd(),
18353
+ externalChannelId
18354
+ });
18355
+ console.log(`[channels] auto-provisioned a new channel for Slack channel ${externalChannelId}`);
18356
+ return created;
18357
+ } catch (err) {
18358
+ await refreshChannelRegistry();
18359
+ const raced = findChannelByExternalId(externalChannelId);
18360
+ if (raced) return raced.profile === getProfile() ? raced : null;
18361
+ throw err;
18362
+ }
18363
+ }
18364
+ async function ensureAgentDmChannel(agentName, viewer, opts) {
18365
+ const existing = findChannelByAgentName(agentName, viewer.userId);
18366
+ if (existing) {
18367
+ return existing.name === opts.name ? existing : updateChannelById(existing.id, { name: opts.name });
18368
+ }
18369
+ const dmKey = agentDmKey(agentName, viewer.userId);
18370
+ try {
18371
+ return await createChannel({
18372
+ name: opts.name,
18373
+ cwd: dmCwd(dmKey),
18374
+ visibility: "private",
18375
+ memberEmails: [viewer.email],
18376
+ agentName,
18377
+ dmKey
18378
+ });
18379
+ } catch (err) {
18380
+ await refreshChannelRegistry();
18381
+ const raced = findChannelByAgentName(agentName, viewer.userId);
18382
+ if (raced) return raced;
18383
+ throw err;
18384
+ }
18385
+ }
18386
+ async function ensureGeneralChannel() {
18387
+ const find = () => getProfileChannelRegistry().find((c) => c.isDefault);
18388
+ const existing = find();
18389
+ if (existing) return existing;
18390
+ try {
18391
+ return await createChannel({
18392
+ name: "general",
18393
+ cwd: `${getProfile()}/general`,
18394
+ visibility: "public",
18395
+ isDefault: true
18396
+ });
18397
+ } catch (err) {
18398
+ await refreshChannelRegistry();
18399
+ const raced = find();
18400
+ if (raced) return raced;
18401
+ throw err;
18402
+ }
18403
+ }
18404
+ async function ensureMemberDmChannel(a, b) {
18405
+ const dmKey = [a.userId, b.userId].sort().join(":");
18406
+ const find = () => [...getProfileChannelRegistry()].find((c) => c.dmKey === dmKey && c.profile === getProfile());
18407
+ const existing = find();
18408
+ if (existing) return existing;
18409
+ try {
18410
+ return await createChannel({
18411
+ name: `${a.handle}, ${b.handle}`,
18412
+ // Hash the whole key: a prefix of the sorted ids is just the first user's
18413
+ // id, which put every DM that user sorts first in into one shared folder.
18414
+ cwd: dmCwd(dmKey),
18415
+ visibility: "private",
18416
+ memberEmails: [a.email, b.email],
18417
+ dmKey
18418
+ });
18419
+ } catch (err) {
18420
+ await refreshChannelRegistry();
18421
+ const raced = find();
18422
+ if (raced) return raced;
18423
+ throw err;
18424
+ }
18425
+ }
18426
+
17909
18427
  // ../api/src/dashboard/auth-context.ts
17910
18428
  import { HTTPException } from "hono/http-exception";
17911
18429
  import { isAuthApiError, isAuthRetryableFetchError } from "@supabase/supabase-js";
@@ -18484,12 +19002,12 @@ async function setAgentPaused(workspaceId, paused) {
18484
19002
 
18485
19003
  // ../api/src/dashboard/auth-context.ts
18486
19004
  function onboardingPending(ctx) {
18487
- const pending2 = [];
18488
- if (!ctx.onboarded && !ctx.passwordSet) pending2.push("account");
18489
- if (!ctx.onboarded) pending2.push("profile");
18490
- if (ctx.role === "admin" && !ctx.agentConnectedAt) pending2.push("agent");
18491
- if (ctx.role === "admin" && !ctx.projectsSetupAt) pending2.push("projects");
18492
- return pending2;
19005
+ const pending = [];
19006
+ if (!ctx.onboarded && !ctx.passwordSet) pending.push("account");
19007
+ if (!ctx.onboarded) pending.push("profile");
19008
+ if (ctx.role === "admin" && !ctx.agentConnectedAt) pending.push("agent");
19009
+ if (ctx.role === "admin" && !ctx.projectsSetupAt) pending.push("projects");
19010
+ return pending;
18493
19011
  }
18494
19012
  var inFlight = /* @__PURE__ */ new Map();
18495
19013
  var CACHE_TTL_MS2 = 3e4;
@@ -18585,8 +19103,8 @@ async function resolveAuthContextUncached(c) {
18585
19103
  }
18586
19104
 
18587
19105
  // ../api/src/dashboard/settings.ts
18588
- import { readFileSync, existsSync } from "fs";
18589
- import { resolve } from "path";
19106
+ import { readFileSync, existsSync as existsSync2 } from "fs";
19107
+ import { resolve as resolve2 } from "path";
18590
19108
 
18591
19109
  // ../api/src/store/workspace-settings-store.ts
18592
19110
  var BRANDING_DEFAULTS = {
@@ -18699,7 +19217,7 @@ function localDefaults() {
18699
19217
  }
18700
19218
  var AUTO_TITLE_PROMPT_MAX = 2e3;
18701
19219
  function readSettingsFile() {
18702
- if (!existsSync(paths.DASHBOARD_SETTINGS_FILE)) return null;
19220
+ if (!existsSync2(paths.DASHBOARD_SETTINGS_FILE)) return null;
18703
19221
  try {
18704
19222
  const raw = JSON.parse(readFileSync(paths.DASHBOARD_SETTINGS_FILE, "utf-8"));
18705
19223
  return raw && typeof raw === "object" ? raw : null;
@@ -18748,15 +19266,15 @@ async function saveWorkspaceBranding(patch, profile = getProfile()) {
18748
19266
  return brandingToSettings(await upsertWorkspaceBranding(profile, next));
18749
19267
  }
18750
19268
  function defaultPromptPath() {
18751
- return resolve(paths.PACKAGE_ROOT, "system.default.md");
19269
+ return resolve2(paths.PACKAGE_ROOT, "system.default.md");
18752
19270
  }
18753
19271
  function readDefaultPrompt() {
18754
19272
  const path = defaultPromptPath();
18755
- return existsSync(path) ? readFileSync(path, "utf-8").trim() : "";
19273
+ return existsSync2(path) ? readFileSync(path, "utf-8").trim() : "";
18756
19274
  }
18757
19275
  function loadWorkspacePrompt() {
18758
19276
  const defaultPrompt = readDefaultPrompt();
18759
- const custom = existsSync(paths.PROMPT_FILE);
19277
+ const custom = existsSync2(paths.PROMPT_FILE);
18760
19278
  return {
18761
19279
  prompt: custom ? readFileSync(paths.PROMPT_FILE, "utf-8").trim() : defaultPrompt,
18762
19280
  defaultPrompt,
@@ -18790,9 +19308,9 @@ async function agentViewer(c) {
18790
19308
 
18791
19309
  // src/claude/agent.ts
18792
19310
  import { spawn } from "child_process";
18793
- import { existsSync as existsSync7, readFileSync as readFileSync3, statSync as statSync2 } from "fs";
19311
+ import { existsSync as existsSync7, readFileSync as readFileSync3, statSync as statSync3 } from "fs";
18794
19312
  import { resolve as resolve4, resolve as resolvePath } from "path";
18795
- import { homedir as homedir2 } from "os";
19313
+ import { homedir as homedir3 } from "os";
18796
19314
  import { randomUUID } from "crypto";
18797
19315
 
18798
19316
  // ../api/src/claude/models.ts
@@ -18899,12 +19417,12 @@ function modelLabel(value) {
18899
19417
 
18900
19418
  // src/claude/container.ts
18901
19419
  import { execFileSync } from "child_process";
18902
- import { createHash } from "crypto";
18903
- import { existsSync as existsSync3, mkdirSync as mkdirSync2 } from "fs";
19420
+ import { createHash as createHash2 } from "crypto";
19421
+ import { existsSync as existsSync4, mkdirSync as mkdirSync3 } from "fs";
18904
19422
  import { join as join2 } from "path";
18905
19423
 
18906
19424
  // src/claude/mounts.ts
18907
- import { existsSync as existsSync2, lstatSync, mkdirSync, readlinkSync, symlinkSync, unlinkSync } from "fs";
19425
+ import { existsSync as existsSync3, lstatSync, mkdirSync as mkdirSync2, readlinkSync, symlinkSync, unlinkSync } from "fs";
18908
19426
  import { basename, join } from "path";
18909
19427
  var MOUNTS_DIR = "mounts";
18910
19428
  function resolveMounts(paths2) {
@@ -18929,11 +19447,11 @@ function materialiseMountLinks(cwd, mounts) {
18929
19447
  if (mounts.length === 0) return [];
18930
19448
  const problems = [];
18931
19449
  const root = join(cwd, MOUNTS_DIR);
18932
- mkdirSync(root, { recursive: true });
19450
+ mkdirSync2(root, { recursive: true });
18933
19451
  for (const repo of mounts) {
18934
19452
  const link = join(root, repo.name);
18935
19453
  try {
18936
- if (existsSync2(link) || isBrokenSymlink(link)) {
19454
+ if (existsSync3(link) || isBrokenSymlink(link)) {
18937
19455
  if (!lstatSync(link).isSymbolicLink()) {
18938
19456
  problems.push(`${link} exists and is not a symlink \u2014 leaving it alone`);
18939
19457
  continue;
@@ -18998,7 +19516,7 @@ function memoryLimit() {
18998
19516
  return process.env["FLYSPACE_AGENT_MEMORY"]?.trim() || "2g";
18999
19517
  }
19000
19518
  function containerHomeFor(cwd) {
19001
- const digest = createHash("sha256").update(cwd).digest("hex").slice(0, 12);
19519
+ const digest = createHash2("sha256").update(cwd).digest("hex").slice(0, 12);
19002
19520
  const label = (cwd.split("/").pop() || "channel").replace(/[^a-zA-Z0-9._-]/g, "-").slice(0, 32);
19003
19521
  return join2(paths.CONTAINER_HOMES_DIR, `${label}-${digest}`);
19004
19522
  }
@@ -19023,7 +19541,7 @@ function rewriteArgsForContainer(args) {
19023
19541
  function buildContainerSpawn(input) {
19024
19542
  const home = containerHomeFor(input.cwd);
19025
19543
  for (const dir of [home, paths.SCRATCH_DIR]) {
19026
- if (!existsSync3(dir)) mkdirSync2(dir, { recursive: true });
19544
+ if (!existsSync4(dir)) mkdirSync3(dir, { recursive: true });
19027
19545
  }
19028
19546
  const containerName = `flyspace-agent-${input.runId}`;
19029
19547
  const env = buildContainerEnv(input.hostEnv);
@@ -19119,21 +19637,21 @@ function userFlags() {
19119
19637
 
19120
19638
  // src/claude/sandbox.ts
19121
19639
  import { execFileSync as execFileSync2 } from "child_process";
19122
- import { createHash as createHash2 } from "crypto";
19123
- import { existsSync as existsSync4, mkdirSync as mkdirSync3, writeFileSync } from "fs";
19640
+ import { createHash as createHash3 } from "crypto";
19641
+ import { existsSync as existsSync5, mkdirSync as mkdirSync4, writeFileSync } from "fs";
19124
19642
  import { join as join3 } from "path";
19125
19643
  function sandboxRuntimeEntrypoint() {
19126
19644
  return join3(paths.PACKAGE_ROOT, "node_modules/@anthropic-ai/sandbox-runtime/dist/cli.js");
19127
19645
  }
19128
19646
  function sandboxHomeFor(cwd) {
19129
- const digest = createHash2("sha256").update(cwd).digest("hex").slice(0, 12);
19647
+ const digest = createHash3("sha256").update(cwd).digest("hex").slice(0, 12);
19130
19648
  const label = (cwd.split("/").pop() || "channel").replace(/[^a-zA-Z0-9._-]/g, "-").slice(0, 32);
19131
19649
  return join3(paths.SANDBOX_HOMES_DIR, `${label}-${digest}`);
19132
19650
  }
19133
19651
  function buildSandboxSpawn(input) {
19134
19652
  const home = sandboxHomeFor(input.cwd);
19135
19653
  for (const dir of [home, paths.SCRATCH_DIR]) {
19136
- if (!existsSync4(dir)) mkdirSync3(dir, { recursive: true });
19654
+ if (!existsSync5(dir)) mkdirSync4(dir, { recursive: true });
19137
19655
  }
19138
19656
  const claudeBin = process.env["FLYSPACE_CLAUDE_BIN"]?.trim() || execFileSync2("which", ["claude"]).toString().trim();
19139
19657
  const allowRead = [input.cwd, home, paths.SCRATCH_DIR, join3(paths.PACKAGE_ROOT, "node_modules")];
@@ -19178,7 +19696,7 @@ function buildSandboxSpawn(input) {
19178
19696
  };
19179
19697
  }
19180
19698
  function sandboxRuntimeStatus() {
19181
- if (existsSync4(sandboxRuntimeEntrypoint())) return { ok: true };
19699
+ if (existsSync5(sandboxRuntimeEntrypoint())) return { ok: true };
19182
19700
  return {
19183
19701
  ok: false,
19184
19702
  message: `This channel runs its agent in a sandbox, but \`@anthropic-ai/sandbox-runtime\` is not installed.
@@ -19299,88 +19817,6 @@ function resolveModelAlias(model) {
19299
19817
  return MODEL_ALIASES[model.toLowerCase()] ?? model;
19300
19818
  }
19301
19819
 
19302
- // ../api/src/config.ts
19303
- import dotenv from "dotenv";
19304
- import { existsSync as existsSync5 } from "fs";
19305
- import { resolve as resolve2 } from "path";
19306
- var DEFAULT_CODEX_MODEL = "";
19307
- function mcpStrictConfigEnabled() {
19308
- return process.env["MCP_STRICT_CONFIG"]?.trim() === "true";
19309
- }
19310
- function loadEnvFiles() {
19311
- if (existsSync5(paths.CONFIG_FILE)) {
19312
- dotenv.config({ path: paths.CONFIG_FILE, override: true, quiet: true });
19313
- }
19314
- const candidates = [resolve2(paths.PACKAGE_ROOT, ".env"), resolve2(process.cwd(), ".env")];
19315
- for (const path of new Set(candidates)) {
19316
- if (existsSync5(path)) {
19317
- dotenv.config({ path, override: false, quiet: true });
19318
- }
19319
- }
19320
- }
19321
- function parseBudget(raw) {
19322
- if (raw === void 0) return 10;
19323
- const n = Number.parseFloat(raw);
19324
- if (!Number.isFinite(n) || n <= 0) return void 0;
19325
- return n;
19326
- }
19327
- function parseEffort(raw) {
19328
- const trimmed = raw?.trim().toLowerCase();
19329
- return trimmed && isEffort(trimmed) ? trimmed : void 0;
19330
- }
19331
- var SLACK_ENV = ["SLACK_BOT_TOKEN", "SLACK_APP_TOKEN", "SLACK_SIGNING_SECRET"];
19332
- function slackConfigured(env = process.env) {
19333
- return SLACK_ENV.some((name) => env[name]?.trim());
19334
- }
19335
- function requireSlackBotToken(config) {
19336
- if (!config.slackBotToken) {
19337
- throw new Error("Slack is not configured: set SLACK_BOT_TOKEN to use Slack commands");
19338
- }
19339
- return config.slackBotToken;
19340
- }
19341
- function requireEnv(name) {
19342
- const value = process.env[name];
19343
- if (!value) {
19344
- throw new Error(`Missing required environment variable: ${name}`);
19345
- }
19346
- return value;
19347
- }
19348
- function loadConfig() {
19349
- const ownerUserId = process.env["OWNER_USER_ID"] || void 0;
19350
- const allowedUserIds = new Set(
19351
- (process.env["ALLOWED_USER_IDS"] ?? "").split(",").map((s) => s.trim()).filter(Boolean)
19352
- );
19353
- if (ownerUserId && allowedUserIds.size > 0) {
19354
- allowedUserIds.add(ownerUserId);
19355
- }
19356
- const autoRespondChannelIds = new Set(
19357
- (process.env["AUTO_RESPOND_CHANNEL_IDS"] ?? "").split(",").map((s) => s.trim()).filter(Boolean)
19358
- );
19359
- const slackEnglishOnlyExemptChannelIds = new Set(
19360
- (process.env["SLACK_ENGLISH_ONLY_EXEMPT_CHANNEL_IDS"] ?? "").split(",").map((s) => s.trim()).filter(Boolean)
19361
- );
19362
- const slack = slackConfigured();
19363
- return {
19364
- slackBotToken: slack ? requireEnv("SLACK_BOT_TOKEN") : void 0,
19365
- slackAppToken: slack ? requireEnv("SLACK_APP_TOKEN") : void 0,
19366
- slackSigningSecret: slack ? requireEnv("SLACK_SIGNING_SECRET") : void 0,
19367
- claudeCwd: process.env["CLAUDE_CWD"] ?? process.cwd(),
19368
- claudeConfigDir: process.env["CLAUDE_CONFIG_DIR"] || void 0,
19369
- claudeCodeOauthToken: process.env["CLAUDE_CODE_OAUTH_TOKEN"] || void 0,
19370
- botName: process.env["BOT_NAME"] ?? "Bot",
19371
- allowedUserIds,
19372
- maxTurns: parseInt(process.env["MAX_TURNS"] ?? "10", 10),
19373
- model: process.env["CUSTIE_MODEL"]?.trim() || "sonnet",
19374
- effort: parseEffort(process.env["CUSTIE_EFFORT"]),
19375
- maxBudgetUsd: parseBudget(process.env["MAX_BUDGET_USD"]),
19376
- ownerUserId,
19377
- autoRespondChannelIds,
19378
- codexModel: process.env["CUSTIE_CODEX_MODEL"]?.trim() || DEFAULT_CODEX_MODEL,
19379
- slackEnglishOnly: process.env["SLACK_ENGLISH_ONLY"] === "true",
19380
- slackEnglishOnlyExemptChannelIds
19381
- };
19382
- }
19383
-
19384
19820
  // ../api/src/utils/mise-env.ts
19385
19821
  import { execFileSync as execFileSync3 } from "child_process";
19386
19822
  function resolveMiseEnv(cwd) {
@@ -19402,9 +19838,9 @@ function readMiseEnv(cwd) {
19402
19838
  }
19403
19839
 
19404
19840
  // ../api/src/store/output-styles-store.ts
19405
- import { existsSync as existsSync6, mkdirSync as mkdirSync4, readdirSync, readFileSync as readFileSync2, renameSync, rmSync, statSync, writeFileSync as writeFileSync2 } from "fs";
19406
- import { homedir } from "os";
19407
- import { join as join4, resolve as resolve3, sep } from "path";
19841
+ import { existsSync as existsSync6, mkdirSync as mkdirSync5, readdirSync, readFileSync as readFileSync2, renameSync, rmSync, statSync as statSync2, writeFileSync as writeFileSync2 } from "fs";
19842
+ import { homedir as homedir2 } from "os";
19843
+ import { join as join4, resolve as resolve3, sep as sep2 } from "path";
19408
19844
  var BUILT_IN_OUTPUT_STYLES = [
19409
19845
  { slug: "default", name: "Default", description: "Claude Code\u2019s standard software engineering prompt." },
19410
19846
  { slug: "proactive", name: "Proactive", description: "Works autonomously and makes reasonable calls instead of asking." },
@@ -19416,7 +19852,7 @@ var OutputStyleConflictError = class extends Error {
19416
19852
  };
19417
19853
  var ID_RE = /^[A-Za-z0-9_-][A-Za-z0-9._-]*$/;
19418
19854
  function resolveDir(claudeConfigDir) {
19419
- return claudeConfigDir || join4(homedir(), ".claude");
19855
+ return claudeConfigDir || join4(homedir2(), ".claude");
19420
19856
  }
19421
19857
  function stylesDir(claudeConfigDir) {
19422
19858
  return join4(resolveDir(claudeConfigDir), "output-styles");
@@ -19425,7 +19861,7 @@ function styleFile(claudeConfigDir, id) {
19425
19861
  if (!ID_RE.test(id)) return null;
19426
19862
  const dir = resolve3(stylesDir(claudeConfigDir));
19427
19863
  const file = resolve3(dir, `${id}.md`);
19428
- return file.startsWith(dir + sep) ? file : null;
19864
+ return file.startsWith(dir + sep2) ? file : null;
19429
19865
  }
19430
19866
  function slugify(name) {
19431
19867
  return name.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "");
@@ -19467,7 +19903,7 @@ ${p.body.trim()}
19467
19903
  `;
19468
19904
  }
19469
19905
  function atomicWrite(file, content) {
19470
- mkdirSync4(resolve3(file, ".."), { recursive: true });
19906
+ mkdirSync5(resolve3(file, ".."), { recursive: true });
19471
19907
  const tmp = `${file}.${process.pid}.tmp`;
19472
19908
  writeFileSync2(tmp, content);
19473
19909
  renameSync(tmp, file);
@@ -19475,7 +19911,7 @@ function atomicWrite(file, content) {
19475
19911
  function readStyle(claudeConfigDir, id) {
19476
19912
  const file = styleFile(claudeConfigDir, id);
19477
19913
  if (!file || !existsSync6(file)) return null;
19478
- const stat = statSync(file);
19914
+ const stat = statSync2(file);
19479
19915
  const p = parseStyle(readFileSync2(file, "utf8"), id);
19480
19916
  return {
19481
19917
  id,
@@ -20145,7 +20581,7 @@ function recordUsage2(response, options) {
20145
20581
  }
20146
20582
  function pinnedClaudeConfigDir(dir) {
20147
20583
  if (!dir) return void 0;
20148
- return resolvePath(dir.replace(/^~(?=\/|$)/, homedir2())) === resolvePath(homedir2(), ".claude") ? void 0 : dir;
20584
+ return resolvePath(dir.replace(/^~(?=\/|$)/, homedir3())) === resolvePath(homedir3(), ".claude") ? void 0 : dir;
20149
20585
  }
20150
20586
  function runCli(prompt, cwd, botName, options, claudeConfigDir, resumeSessionId, claudeCodeOauthToken) {
20151
20587
  return new Promise((resolve8, reject) => {
@@ -20397,7 +20833,7 @@ function runCli(prompt, cwd, botName, options, claudeConfigDir, resumeSessionId,
20397
20833
  });
20398
20834
  }
20399
20835
  async function askClaude(prompt, cwd, botName, options, claudeConfigDir, resumeSessionId, claudeCodeOauthToken) {
20400
- if (!existsSync7(cwd) || !statSync2(cwd).isDirectory()) {
20836
+ if (!existsSync7(cwd) || !statSync3(cwd).isDirectory()) {
20401
20837
  console.error(`[agent] working directory does not exist: ${cwd}`);
20402
20838
  return {
20403
20839
  sessionId: resumeSessionId ?? "",
@@ -20467,6 +20903,131 @@ Fix the channel's working directory in its settings (or recreate the directory),
20467
20903
  }
20468
20904
  }
20469
20905
 
20906
+ // ../api/src/store/authors.ts
20907
+ var AGENT_AUTHOR = "agent";
20908
+ var SYNCED_BOT_AUTHOR = "Bot";
20909
+ var LEGACY_BOT_AUTHOR = "Custie";
20910
+ var SUPPORT_BOT_AUTHOR = "Flyspace Support";
20911
+ var NON_HUMAN_AUTHORS = new Set(
20912
+ [AGENT_AUTHOR, SYNCED_BOT_AUTHOR, LEGACY_BOT_AUTHOR, SUPPORT_BOT_AUTHOR].map((a) => a.toLowerCase())
20913
+ );
20914
+ function isHumanAuthor(author) {
20915
+ return !NON_HUMAN_AUTHORS.has(author.toLowerCase());
20916
+ }
20917
+
20918
+ // ../api/src/store/thread-title.ts
20919
+ var TITLE_MAX_LENGTH = 80;
20920
+ function deriveThreadTitle(text) {
20921
+ const firstLine = text.split("\n").find((line) => line.trim().length > 0);
20922
+ if (!firstLine) return null;
20923
+ const cleaned = firstLine.replace(/^\s*(?::[a-z0-9_+-]+:\s*)+/i, "").replace(/^\s*\p{Extended_Pictographic}[️‍]*\s*/u, "").replace(/\*\*([^*]+)\*\*/g, "$1").replace(/\*([^*]+)\*/g, "$1").replace(/(^|\s)_([^_\n]+)_(?=\s|$|[.,:;,。、:])/g, "$1$2").replace(/`([^`]+)`/g, "$1").replace(/\s+/g, " ").trim();
20924
+ if (!cleaned) return null;
20925
+ return cleaned.length > TITLE_MAX_LENGTH ? `${cleaned.slice(0, TITLE_MAX_LENGTH).trim()}\u2026` : cleaned;
20926
+ }
20927
+
20928
+ // src/store/dashboard-sync.ts
20929
+ async function syncPostToDashboard(opts) {
20930
+ const { channelId, ts: ts3, threadTs, text } = opts;
20931
+ if (!databaseReachable()) {
20932
+ console.warn("[dashboard-sync] Supabase not configured \u2014 skipping dashboard sync");
20933
+ return;
20934
+ }
20935
+ try {
20936
+ const supabase = getSupabaseClient();
20937
+ const dashboardChannelId = await resolveDashboardChannelId(supabase, channelId);
20938
+ const threadId = threadTs ? await ensureThreadId(supabase, channelId, dashboardChannelId, threadTs) : await createOwnThread(supabase, channelId, dashboardChannelId, ts3, text);
20939
+ const { error } = await supabase.from("thread_replies").upsert(
20940
+ {
20941
+ thread_id: threadId,
20942
+ // This mirror only ever runs for the bot's own posts (automation
20943
+ // output, `flyspace slack post`), so the author is the agent itself —
20944
+ // labelling it anything else makes the chat agent count it as a
20945
+ // second human and stop replying without an explicit mention.
20946
+ author: AGENT_AUTHOR,
20947
+ body: await uploadLocalImages(text),
20948
+ external_thread_replies_id: `${channelId}:${ts3}`
20949
+ },
20950
+ { onConflict: "external_thread_replies_id" }
20951
+ );
20952
+ if (error) {
20953
+ console.warn(`[dashboard-sync] failed to write reply: ${error.message}`);
20954
+ }
20955
+ } catch (err) {
20956
+ console.warn(
20957
+ `[dashboard-sync] sync failed: ${err instanceof Error ? err.message : String(err)}`
20958
+ );
20959
+ }
20960
+ }
20961
+ async function resolveDashboardChannelId(supabase, slackChannelId) {
20962
+ const { data, error } = await supabase.from("channels").select("id").eq("external_channel_id", slackChannelId).maybeSingle();
20963
+ if (error || !data) return slackChannelId;
20964
+ return data["id"];
20965
+ }
20966
+ async function createOwnThread(supabase, externalChannelId, dashboardChannelId, ts3, text) {
20967
+ const { data, error } = await supabase.from("threads").upsert(
20968
+ {
20969
+ channel_id: dashboardChannelId,
20970
+ title: deriveThreadTitle(text),
20971
+ author: AGENT_AUTHOR,
20972
+ external_thread_id: `${externalChannelId}:${ts3}`
20973
+ },
20974
+ { onConflict: "external_thread_id" }
20975
+ ).select("id").single();
20976
+ if (error || !data) throw new Error(error?.message ?? "failed to create thread");
20977
+ return data["id"];
20978
+ }
20979
+ async function ensureThreadId(supabase, externalChannelId, dashboardChannelId, parentTs) {
20980
+ const key = `${externalChannelId}:${parentTs}`;
20981
+ const { data: existing, error: selectError } = await supabase.from("threads").select("id").eq("external_thread_id", key).maybeSingle();
20982
+ if (selectError) throw new Error(selectError.message);
20983
+ if (existing) return existing["id"];
20984
+ const { data: created, error: createError } = await supabase.from("threads").upsert(
20985
+ // The unsynced parent could be anyone's message (often another bot's),
20986
+ // so keep the generic non-human placeholder rather than claiming it.
20987
+ {
20988
+ channel_id: dashboardChannelId,
20989
+ title: null,
20990
+ author: SYNCED_BOT_AUTHOR,
20991
+ external_thread_id: key
20992
+ },
20993
+ { onConflict: "external_thread_id" }
20994
+ ).select("id").single();
20995
+ if (createError || !created) {
20996
+ throw new Error(createError?.message ?? "failed to create placeholder thread");
20997
+ }
20998
+ return created["id"];
20999
+ }
21000
+
21001
+ // src/store/dashboard-post.ts
21002
+ async function postToDashboardChannel(opts) {
21003
+ const { channelId, text, threadId, title } = opts;
21004
+ const supabase = getSupabaseClient();
21005
+ if (!threadId && !channelId) {
21006
+ throw new Error("postToDashboardChannel: channelId is required to start a new thread");
21007
+ }
21008
+ const parentId = threadId ?? await createThread(supabase, channelId, text, title);
21009
+ const body = await uploadLocalImages(text);
21010
+ const { data, error } = await supabase.from("thread_replies").insert({ thread_id: parentId, author: AGENT_AUTHOR, body }).select("id").single();
21011
+ if (error || !data) {
21012
+ throw new Error(`failed to write dashboard reply: ${error?.message ?? "no row returned"}`);
21013
+ }
21014
+ return { threadId: parentId, replyId: data["id"] };
21015
+ }
21016
+ async function createThread(supabase, channelId, text, title) {
21017
+ const { data, error } = await supabase.from("threads").insert({
21018
+ channel_id: channelId,
21019
+ // An untitled thread is effectively invisible in the sidebar, so give a
21020
+ // daily report the same first-line-derived title a mirrored post gets,
21021
+ // unless the caller named the thread itself.
21022
+ title: title?.trim().replace(/\\([\\`*_{}[\]()#+\-.!~>|])/g, "$1") || deriveThreadTitle(text),
21023
+ author: AGENT_AUTHOR
21024
+ }).select("id").single();
21025
+ if (error || !data) {
21026
+ throw new Error(`failed to create dashboard thread: ${error?.message ?? "no row returned"}`);
21027
+ }
21028
+ return data["id"];
21029
+ }
21030
+
20470
21031
  // src/automations/scheduler.ts
20471
21032
  import cron2 from "node-cron";
20472
21033
  import { CronExpressionParser } from "cron-parser";
@@ -20508,8 +21069,8 @@ function automationToRow(type, item, position) {
20508
21069
  };
20509
21070
  }
20510
21071
  var rows = [];
20511
- var changeListeners = /* @__PURE__ */ new Set();
20512
- var lastSnapshot;
21072
+ var changeListeners2 = /* @__PURE__ */ new Set();
21073
+ var lastSnapshot2;
20513
21074
  async function refreshAutomationRegistry() {
20514
21075
  const { data, error } = await getSupabaseClient().from("automations").select("*").order("position", { ascending: true });
20515
21076
  if (error) {
@@ -20518,10 +21079,10 @@ async function refreshAutomationRegistry() {
20518
21079
  }
20519
21080
  const next = data ?? [];
20520
21081
  const snapshot2 = JSON.stringify(next, (key, value) => key === "updated_at" ? void 0 : value);
20521
- if (snapshot2 === lastSnapshot) return;
20522
- lastSnapshot = snapshot2;
21082
+ if (snapshot2 === lastSnapshot2) return;
21083
+ lastSnapshot2 = snapshot2;
20523
21084
  rows = next;
20524
- for (const cb of changeListeners) {
21085
+ for (const cb of changeListeners2) {
20525
21086
  try {
20526
21087
  cb();
20527
21088
  } catch (err) {
@@ -20530,8 +21091,8 @@ async function refreshAutomationRegistry() {
20530
21091
  }
20531
21092
  }
20532
21093
  function onAutomationRegistryChange(cb) {
20533
- changeListeners.add(cb);
20534
- return () => changeListeners.delete(cb);
21094
+ changeListeners2.add(cb);
21095
+ return () => changeListeners2.delete(cb);
20535
21096
  }
20536
21097
  function profileRows() {
20537
21098
  const profile = getProfile();
@@ -20587,14 +21148,14 @@ async function setAutomationEnabled(name, enabled) {
20587
21148
  if (error) throw new Error(`Failed to update automation "${name}": ${error.message}`);
20588
21149
  await refreshAutomationRegistry();
20589
21150
  }
20590
- var DEFAULT_POLL_INTERVAL_MS = 2e4;
20591
- var pollTimer;
20592
- var realtimeChannel;
20593
- function startAutomationRegistryPolling(intervalMs = DEFAULT_POLL_INTERVAL_MS) {
21151
+ var DEFAULT_POLL_INTERVAL_MS2 = 2e4;
21152
+ var pollTimer2;
21153
+ var realtimeChannel2;
21154
+ function startAutomationRegistryPolling(intervalMs = DEFAULT_POLL_INTERVAL_MS2) {
20594
21155
  stopAutomationRegistryPolling();
20595
- pollTimer = setInterval(() => void refreshAutomationRegistry(), intervalMs);
21156
+ pollTimer2 = setInterval(() => void refreshAutomationRegistry(), intervalMs);
20596
21157
  try {
20597
- realtimeChannel = getSupabaseClient().channel("automations-registry").on(
21158
+ realtimeChannel2 = getSupabaseClient().channel("automations-registry").on(
20598
21159
  "postgres_changes",
20599
21160
  { event: "*", schema: "public", table: "automations" },
20600
21161
  () => void refreshAutomationRegistry()
@@ -20608,11 +21169,11 @@ function startAutomationRegistryPolling(intervalMs = DEFAULT_POLL_INTERVAL_MS) {
20608
21169
  return stopAutomationRegistryPolling;
20609
21170
  }
20610
21171
  function stopAutomationRegistryPolling() {
20611
- if (pollTimer) clearInterval(pollTimer);
20612
- pollTimer = void 0;
20613
- if (realtimeChannel) {
20614
- void getSupabaseClient().removeChannel(realtimeChannel);
20615
- realtimeChannel = void 0;
21172
+ if (pollTimer2) clearInterval(pollTimer2);
21173
+ pollTimer2 = void 0;
21174
+ if (realtimeChannel2) {
21175
+ void getSupabaseClient().removeChannel(realtimeChannel2);
21176
+ realtimeChannel2 = void 0;
20616
21177
  }
20617
21178
  }
20618
21179
 
@@ -21056,454 +21617,12 @@ async function runCompanion(config, userId, slot) {
21056
21617
  }
21057
21618
 
21058
21619
  // src/commands/persona.ts
21059
- import { execFileSync as execFileSync5 } from "child_process";
21060
- import { createHash as createHash3 } from "crypto";
21061
- import { existsSync as existsSync9, mkdtempSync as mkdtempSync2, readdirSync as readdirSync2, readFileSync as readFileSync6, renameSync as renameSync2, rmSync as rmSync5, writeFileSync as writeFileSync5 } from "fs";
21062
- import { homedir as homedir3 } from "os";
21063
- import { basename as basename2, join as join8 } from "path";
21064
- import sharp from "sharp";
21065
-
21066
- // src/auth/device-auth.ts
21067
- import { createPrivateKey, createPublicKey, generateKeyPairSync, sign } from "crypto";
21068
- import { existsSync as existsSync8, mkdirSync as mkdirSync5, readFileSync as readFileSync4, rmSync as rmSync3, writeFileSync as writeFileSync3 } from "fs";
21069
- import { dirname, join as join6 } from "path";
21070
- var DEFAULT_API_URL = "https://app.flyspace.ai";
21071
- var EXPIRY_SKEW_MS = 6e4;
21072
- var AuthApiError = class extends Error {
21073
- constructor(message, status) {
21074
- super(message);
21075
- this.status = status;
21076
- this.name = "AuthApiError";
21077
- }
21078
- };
21079
- function apiUrl() {
21080
- return (process.env["FLYSPACE_API_URL"] || DEFAULT_API_URL).replace(/\/+$/, "");
21081
- }
21082
- function deviceKeyPath() {
21083
- return join6(paths.BASE_CONFIG_DIR, "device.key");
21084
- }
21085
- function credentialsPath() {
21086
- return join6(paths.BASE_CONFIG_DIR, "credentials.json");
21087
- }
21088
- function ensureDeviceKey(path = deviceKeyPath()) {
21089
- let created = false;
21090
- if (!existsSync8(path)) {
21091
- const { privateKey: privateKey2 } = generateKeyPairSync("ed25519");
21092
- mkdirSync5(dirname(path), { recursive: true });
21093
- writeFileSync3(path, privateKey2.export({ type: "pkcs8", format: "pem" }), { mode: 384 });
21094
- created = true;
21095
- }
21096
- const privateKey = createPrivateKey(readFileSync4(path, "utf8"));
21097
- const publicKeyBase64 = createPublicKey(privateKey).export({ type: "spki", format: "der" }).toString(
21098
- "base64"
21099
- );
21100
- return { privateKey, publicKeyBase64, created };
21101
- }
21102
- function loadCredentials(path = credentialsPath()) {
21103
- if (!existsSync8(path)) return null;
21104
- try {
21105
- return JSON.parse(readFileSync4(path, "utf8"));
21106
- } catch {
21107
- return null;
21108
- }
21109
- }
21110
- function saveCredentials(creds, path = credentialsPath()) {
21111
- mkdirSync5(dirname(path), { recursive: true });
21112
- writeFileSync3(path, `${JSON.stringify(creds, null, 2)}
21113
- `, { mode: 384 });
21114
- }
21115
- function clearLocalAuth() {
21116
- rmSync3(credentialsPath(), { force: true });
21117
- rmSync3(deviceKeyPath(), { force: true });
21118
- }
21119
- async function post(base, path, body, token) {
21120
- return fetch(`${base}${path}`, {
21121
- method: "POST",
21122
- headers: {
21123
- "content-type": "application/json",
21124
- ...token ? { authorization: `Bearer ${token}` } : {}
21125
- },
21126
- body: JSON.stringify(body)
21127
- });
21128
- }
21129
- async function readJson(res) {
21130
- try {
21131
- return await res.json();
21132
- } catch {
21133
- return {};
21134
- }
21135
- }
21136
- async function expectOk(res, what) {
21137
- const json = await readJson(res);
21138
- if (!res.ok) {
21139
- const reason = typeof json["error"] === "string" ? json["error"] : res.statusText;
21140
- throw new AuthApiError(`${what} failed (${res.status}): ${reason}`, res.status);
21141
- }
21142
- return json;
21143
- }
21144
- function toSlugs(value) {
21145
- return Array.isArray(value) ? value.filter((v) => typeof v === "string") : [];
21146
- }
21147
- function toGrant(json) {
21148
- const user = json["user"] ?? {};
21149
- return {
21150
- accessToken: String(json["access_token"]),
21151
- expiresIn: Number(json["expires_in"]),
21152
- deviceId: String(json["device_id"]),
21153
- userEmail: String(user["email"] ?? ""),
21154
- workspaces: toSlugs(json["workspaces"])
21155
- };
21156
- }
21157
- async function requestDeviceCode(base, input) {
21158
- const res = await post(base, "/api/auth/device/code", {
21159
- public_key: input.publicKey,
21160
- name: input.name,
21161
- platform: input.platform
21162
- });
21163
- const json = await expectOk(res, "Requesting a device code");
21164
- return {
21165
- deviceCode: String(json["device_code"]),
21166
- userCode: String(json["user_code"]),
21167
- verificationUri: String(json["verification_uri"]),
21168
- expiresIn: Number(json["expires_in"]),
21169
- interval: Number(json["interval"] ?? 5)
21170
- };
21171
- }
21172
- async function pollDeviceToken(base, deviceCode) {
21173
- const res = await post(base, "/api/auth/device/token", { device_code: deviceCode });
21174
- const json = await readJson(res);
21175
- if (res.ok) return { status: "approved", grant: toGrant(json) };
21176
- switch (json["error"]) {
21177
- case "authorization_pending":
21178
- return { status: "pending" };
21179
- case "slow_down":
21180
- return { status: "slow_down" };
21181
- case "access_denied":
21182
- return { status: "denied" };
21183
- case "expired_token":
21184
- return { status: "expired" };
21185
- default:
21186
- throw new AuthApiError(`Polling for approval failed (${res.status}): ${String(json["error"] ?? res.statusText)}`, res.status);
21187
- }
21188
- }
21189
- async function refreshAccessToken(creds, privateKey) {
21190
- const challenge = await expectOk(
21191
- await post(creds.apiUrl, "/api/auth/device/challenge", { device_id: creds.deviceId }),
21192
- "Requesting a refresh challenge"
21193
- );
21194
- const nonce = String(challenge["nonce"]);
21195
- const signature = sign(null, Buffer.from(nonce), privateKey).toString("base64");
21196
- const json = await expectOk(
21197
- await post(creds.apiUrl, "/api/auth/device/refresh", { device_id: creds.deviceId, nonce, signature }),
21198
- "Refreshing the access token"
21199
- );
21200
- return {
21201
- ...creds,
21202
- accessToken: String(json["access_token"]),
21203
- accessTokenExpiresAt: Date.now() + Number(json["expires_in"]) * 1e3
21204
- };
21205
- }
21206
- async function fetchWhoAmI(base, token) {
21207
- const res = await fetch(`${base}/api/auth/device/me`, { headers: { authorization: `Bearer ${token}` } });
21208
- const json = await expectOk(res, "Checking the session");
21209
- const user = json["user"] ?? {};
21210
- const device = json["device"] ?? {};
21211
- return {
21212
- userEmail: String(user["email"] ?? ""),
21213
- deviceId: String(device["id"] ?? ""),
21214
- deviceName: String(device["name"] ?? ""),
21215
- workspaces: toSlugs(json["workspaces"])
21216
- };
21217
- }
21218
- async function boundWorkspaces() {
21219
- const creds = loadCredentials();
21220
- if (!creds) return null;
21221
- try {
21222
- const me = await fetchWhoAmI(creds.apiUrl, await getAccessToken());
21223
- saveCredentials({ ...loadCredentials() ?? creds, workspaces: me.workspaces });
21224
- return { workspaces: me.workspaces, fresh: true };
21225
- } catch {
21226
- return { workspaces: creds.workspaces ?? [], fresh: false };
21227
- }
21228
- }
21229
- async function revokeDevice(base, token) {
21230
- await expectOk(await post(base, "/api/auth/device/revoke", {}, token), "Revoking this device");
21231
- }
21232
- async function getAccessToken() {
21233
- const fromEnv = process.env["FLYSPACE_TOKEN"];
21234
- if (fromEnv) return fromEnv;
21235
- const creds = loadCredentials();
21236
- if (!creds) return null;
21237
- if (creds.accessTokenExpiresAt - EXPIRY_SKEW_MS > Date.now()) return creds.accessToken;
21238
- const { privateKey } = ensureDeviceKey();
21239
- const refreshed = await refreshAccessToken(creds, privateKey);
21240
- saveCredentials(refreshed);
21241
- return refreshed.accessToken;
21242
- }
21243
-
21244
- // src/dashboard/host-db-client.ts
21245
- import { createClient } from "@supabase/supabase-js";
21246
- import { randomUUID as randomUUID2 } from "crypto";
21247
-
21248
- // src/dashboard/host-lock.ts
21249
21620
  import { execFileSync as execFileSync4 } from "child_process";
21250
- import { randomBytes } from "crypto";
21251
- import { mkdirSync as mkdirSync6, readFileSync as readFileSync5, rmSync as rmSync4, writeFileSync as writeFileSync4 } from "fs";
21252
- import { join as join7 } from "path";
21253
- function hostLockPath() {
21254
- return join7(paths.BASE_DATA_DIR, "host.lock");
21255
- }
21256
- function isLiveFlyspace(pid) {
21257
- try {
21258
- process.kill(pid, 0);
21259
- const command = execFileSync4("ps", ["-p", String(pid), "-o", "command="], {
21260
- encoding: "utf8"
21261
- });
21262
- return command.includes("flyspace") || command.includes("host-server");
21263
- } catch {
21264
- return false;
21265
- }
21266
- }
21267
- function readLockPid(path) {
21268
- try {
21269
- const pid = Number(JSON.parse(readFileSync5(path, "utf8")).pid);
21270
- return Number.isInteger(pid) && pid > 0 ? pid : null;
21271
- } catch {
21272
- return null;
21273
- }
21274
- }
21275
- function acquireHostLock() {
21276
- const path = hostLockPath();
21277
- mkdirSync6(paths.BASE_DATA_DIR, { recursive: true });
21278
- const body = JSON.stringify({
21279
- pid: process.pid,
21280
- startedAt: (/* @__PURE__ */ new Date()).toISOString(),
21281
- execPath: process.argv[1] ?? ""
21282
- });
21283
- for (let attempt = 0; attempt < 2; attempt++) {
21284
- try {
21285
- writeFileSync4(path, body, { flag: "wx", mode: 384 });
21286
- const release = () => {
21287
- if (readLockPid(path) === process.pid) rmSync4(path, { force: true });
21288
- };
21289
- process.once("exit", release);
21290
- return release;
21291
- } catch (err) {
21292
- if (err.code !== "EEXIST") throw err;
21293
- const holder = readLockPid(path);
21294
- if (holder === process.pid) return () => {
21295
- };
21296
- if (holder && isLiveFlyspace(holder)) {
21297
- throw new Error(
21298
- `Another Flyspace Host is already running on this machine (pid ${holder}). Stop it first, or check for a second CLI install (\`which -a flyspace\`). Two Hosts overwrite each other's skill mirror.`
21299
- );
21300
- }
21301
- rmSync4(path, { force: true });
21302
- }
21303
- }
21304
- throw new Error(`Could not take the Host lock at ${path}`);
21305
- }
21306
- function publishHostEndpoint(port) {
21307
- const path = hostLockPath();
21308
- if (readLockPid(path) !== process.pid) return null;
21309
- const token = randomBytes(32).toString("hex");
21310
- const lock = JSON.parse(readFileSync5(path, "utf8"));
21311
- writeFileSync4(path, JSON.stringify({ ...lock, port, token }), { mode: 384 });
21312
- return token;
21313
- }
21314
- function readHostEndpoint() {
21315
- try {
21316
- const { pid, port, token } = JSON.parse(readFileSync5(hostLockPath(), "utf8"));
21317
- if (pid === process.pid || !Number.isInteger(port) || typeof token !== "string") return null;
21318
- return { port, token };
21319
- } catch {
21320
- return null;
21321
- }
21322
- }
21323
-
21324
- // src/dashboard/host-db-client.ts
21325
- var REQUEST_TIMEOUT_MS2 = 3e4;
21326
- var pending = /* @__PURE__ */ new Map();
21327
- var sender = null;
21328
- var onSender = [];
21329
- function setHostDbSender(fn) {
21330
- sender = fn;
21331
- if (!fn) return;
21332
- const waiting = onSender;
21333
- onSender = [];
21334
- for (const wake of waiting) wake();
21335
- }
21336
- function sendAgentFailure(report) {
21337
- sender?.({ type: "agent-failure", ...report });
21338
- }
21339
- function handleHostDbResult(id, res) {
21340
- const p = pending.get(id);
21341
- if (!p) return;
21342
- pending.delete(id);
21343
- clearTimeout(p.timer);
21344
- p.resolve(res);
21345
- }
21346
- function whenConnected() {
21347
- if (sender) return Promise.resolve(sender);
21348
- return new Promise((resolve8, reject) => {
21349
- const timer = setTimeout(() => {
21350
- onSender = onSender.filter((w) => w !== wake);
21351
- reject(new Error("Host is not connected to the Data API"));
21352
- }, REQUEST_TIMEOUT_MS2);
21353
- const wake = () => {
21354
- clearTimeout(timer);
21355
- resolve8(sender);
21356
- };
21357
- onSender.push(wake);
21358
- });
21359
- }
21360
- async function requestHostDb(req) {
21361
- const send = await whenConnected();
21362
- const id = randomUUID2();
21363
- return new Promise((resolve8, reject) => {
21364
- const timer = setTimeout(() => {
21365
- pending.delete(id);
21366
- reject(new Error("Data API did not answer in time"));
21367
- }, REQUEST_TIMEOUT_MS2);
21368
- pending.set(id, { resolve: resolve8, reject, timer });
21369
- send({ type: "db", id, req });
21370
- });
21371
- }
21372
- var pendingUrls = /* @__PURE__ */ new Map();
21373
- function handleAttachmentUrlResult(id, url) {
21374
- pendingUrls.get(id)?.(url);
21375
- pendingUrls.delete(id);
21376
- }
21377
- async function requestAttachmentUrl(key) {
21378
- const send = await whenConnected();
21379
- const id = randomUUID2();
21380
- return new Promise((resolve8, reject) => {
21381
- const timer = setTimeout(() => {
21382
- pendingUrls.delete(id);
21383
- reject(new Error("Data API did not answer in time"));
21384
- }, REQUEST_TIMEOUT_MS2);
21385
- pendingUrls.set(id, (url) => {
21386
- clearTimeout(timer);
21387
- resolve8(url);
21388
- });
21389
- send({ type: "attachment-url", id, key });
21390
- });
21391
- }
21392
- var pendingSvgs = /* @__PURE__ */ new Map();
21393
- function handlePluginSvgResult(id, url) {
21394
- pendingSvgs.get(id)?.(url);
21395
- pendingSvgs.delete(id);
21396
- }
21397
- async function requestPluginSvg(workspace, svg) {
21398
- const send = await whenConnected();
21399
- const id = randomUUID2();
21400
- return new Promise((resolve8, reject) => {
21401
- const timer = setTimeout(() => {
21402
- pendingSvgs.delete(id);
21403
- reject(new Error("Data API did not answer in time"));
21404
- }, REQUEST_TIMEOUT_MS2);
21405
- pendingSvgs.set(id, (url) => {
21406
- clearTimeout(timer);
21407
- resolve8(url);
21408
- });
21409
- send({ type: "plugin-svg", id, workspace, svg });
21410
- });
21411
- }
21412
- var pendingRespond = /* @__PURE__ */ new Map();
21413
- function handleShouldRespondResult(id, respond) {
21414
- pendingRespond.get(id)?.(respond);
21415
- pendingRespond.delete(id);
21416
- }
21417
- async function requestShouldRespond(transcript) {
21418
- const send = await whenConnected().catch(() => null);
21419
- if (!send) return false;
21420
- const id = randomUUID2();
21421
- return new Promise((resolve8) => {
21422
- const timer = setTimeout(() => {
21423
- pendingRespond.delete(id);
21424
- resolve8(false);
21425
- }, REQUEST_TIMEOUT_MS2);
21426
- pendingRespond.set(id, (respond) => {
21427
- clearTimeout(timer);
21428
- resolve8(respond);
21429
- });
21430
- send({ type: "should-respond", id, transcript });
21431
- });
21432
- }
21433
- var BODYLESS_STATUS = /* @__PURE__ */ new Set([101, 204, 205, 304]);
21434
- function dbFetch(send) {
21435
- return async (input, init) => {
21436
- const req = new Request(input, init);
21437
- const url = new URL(req.url);
21438
- const method = req.method.toUpperCase();
21439
- const res = await send({
21440
- method,
21441
- path: `${url.pathname}${url.search}`,
21442
- headers: Object.fromEntries(req.headers.entries()),
21443
- body: method === "GET" || method === "HEAD" ? void 0 : await req.text()
21444
- });
21445
- const noBody = method === "HEAD" || BODYLESS_STATUS.has(res.status);
21446
- return new Response(noBody ? null : res.body, { status: res.status, headers: res.headers });
21447
- };
21448
- }
21449
- var hostDbFetch = dbFetch(requestHostDb);
21450
- var LOCAL_DB_PATH = "/internal/db";
21451
- async function requestViaLocalHost(req) {
21452
- const deadline = Date.now() + REQUEST_TIMEOUT_MS2;
21453
- let endpoint = readHostEndpoint();
21454
- while (!endpoint && Date.now() < deadline) {
21455
- await new Promise((r) => setTimeout(r, 1e3));
21456
- endpoint = readHostEndpoint();
21457
- }
21458
- if (!endpoint) throw new Error("No local Host to reach the Data API through");
21459
- const res = await fetch(`http://127.0.0.1:${endpoint.port}${LOCAL_DB_PATH}`, {
21460
- method: "POST",
21461
- headers: { authorization: `Bearer ${endpoint.token}`, "content-type": "application/json" },
21462
- body: JSON.stringify(req),
21463
- signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS2 + 5e3)
21464
- });
21465
- if (!res.ok) throw new Error(`Local Host DB relay answered ${res.status}`);
21466
- return await res.json();
21467
- }
21468
- function relayChannel(topic) {
21469
- const channel = {
21470
- on: () => channel,
21471
- subscribe: (callback) => {
21472
- queueMicrotask(() => callback?.("SUBSCRIBED"));
21473
- return channel;
21474
- },
21475
- send: async (msg) => {
21476
- if (msg.type !== "broadcast" || !sender) return "error";
21477
- sender({ type: "db-broadcast", topic, event: msg.event, payload: msg.payload ?? {} });
21478
- return "ok";
21479
- },
21480
- unsubscribe: async () => "ok"
21481
- };
21482
- return channel;
21483
- }
21484
- function createHostDbClient(via = "socket") {
21485
- const client = createClient("https://host-db.invalid", "host-device", {
21486
- auth: { persistSession: false, autoRefreshToken: false },
21487
- global: { fetch: via === "socket" ? hostDbFetch : dbFetch(requestViaLocalHost) }
21488
- });
21489
- return new Proxy(client, {
21490
- get(target, prop) {
21491
- if (prop === "channel") return relayChannel;
21492
- if (prop === "removeChannel") return async () => "ok";
21493
- const value = Reflect.get(target, prop, target);
21494
- return typeof value === "function" ? value.bind(target) : value;
21495
- }
21496
- });
21497
- }
21498
-
21499
- // src/commands/supabase-via-host.ts
21500
- function useHostDbWithoutCredentials() {
21501
- const viaHost = !!loadCredentials() && (!hasSupabaseCredentials() || !!readHostEndpoint());
21502
- if (viaHost) setSupabaseClient(createHostDbClient("local-host"));
21503
- return viaHost;
21504
- }
21505
-
21506
- // src/commands/persona.ts
21621
+ import { createHash as createHash4 } from "crypto";
21622
+ import { existsSync as existsSync8, mkdtempSync as mkdtempSync2, readdirSync as readdirSync2, readFileSync as readFileSync4, renameSync as renameSync2, rmSync as rmSync3, writeFileSync as writeFileSync3 } from "fs";
21623
+ import { homedir as homedir4 } from "os";
21624
+ import { basename as basename2, join as join6 } from "path";
21625
+ import sharp from "sharp";
21507
21626
  var USAGE = `
21508
21627
  Usage: flyspace persona avatars [--character <id>] [--clear]
21509
21628
 
@@ -21534,34 +21653,34 @@ var PACKS = {
21534
21653
  }
21535
21654
  };
21536
21655
  function pluginInstalled() {
21537
- const claudeDir = process.env["CLAUDE_CONFIG_DIR"] || join8(homedir3(), ".claude");
21538
- return existsSync9(join8(claudeDir, "plugins", "cache", "claudecafe", "persona-panel"));
21656
+ const claudeDir = process.env["CLAUDE_CONFIG_DIR"] || join6(homedir4(), ".claude");
21657
+ return existsSync8(join6(claudeDir, "plugins", "cache", "claudecafe", "persona-panel"));
21539
21658
  }
21540
21659
  function installPack(root, character) {
21541
21660
  const pack = PACKS[character];
21542
21661
  if (!pack) throw new Error(`No published pack for "${character}".`);
21543
- const charactersDir = join8(root, "characters");
21544
- execFileSync5("mkdir", ["-p", charactersDir]);
21545
- const staging = mkdtempSync2(join8(charactersDir, `.${character}-`));
21662
+ const charactersDir = join6(root, "characters");
21663
+ execFileSync4("mkdir", ["-p", charactersDir]);
21664
+ const staging = mkdtempSync2(join6(charactersDir, `.${character}-`));
21546
21665
  try {
21547
- const zip = join8(staging, "pack.zip");
21548
- execFileSync5("curl", ["-fsSL", "--max-time", "60", "-o", zip, pack.url]);
21549
- const digest = createHash3("sha256").update(readFileSync6(zip)).digest("hex");
21666
+ const zip = join6(staging, "pack.zip");
21667
+ execFileSync4("curl", ["-fsSL", "--max-time", "60", "-o", zip, pack.url]);
21668
+ const digest = createHash4("sha256").update(readFileSync4(zip)).digest("hex");
21550
21669
  if (digest !== pack.sha256) throw new Error(`${character} pack SHA-256 mismatch`);
21551
- execFileSync5("unzip", ["-q", zip, "-d", staging]);
21552
- const folder = join8(charactersDir, character);
21553
- if (existsSync9(folder)) renameSync2(folder, join8(staging, "previous"));
21554
- renameSync2(join8(staging, character), folder);
21670
+ execFileSync4("unzip", ["-q", zip, "-d", staging]);
21671
+ const folder = join6(charactersDir, character);
21672
+ if (existsSync8(folder)) renameSync2(folder, join6(staging, "previous"));
21673
+ renameSync2(join6(staging, character), folder);
21555
21674
  } finally {
21556
- rmSync5(staging, { recursive: true, force: true });
21675
+ rmSync3(staging, { recursive: true, force: true });
21557
21676
  }
21558
21677
  }
21559
21678
  function cafeRoot() {
21560
- return join8(process.env["XDG_CONFIG_HOME"] || join8(homedir3(), ".config"), "claudecafe");
21679
+ return join6(process.env["XDG_CONFIG_HOME"] || join6(homedir4(), ".config"), "claudecafe");
21561
21680
  }
21562
21681
  function configuredCharacter(root) {
21563
21682
  try {
21564
- const config = JSON.parse(readFileSync6(join8(root, "config.json"), "utf8"));
21683
+ const config = JSON.parse(readFileSync4(join6(root, "config.json"), "utf8"));
21565
21684
  if (config.character && config.character !== "none") return config.character;
21566
21685
  } catch {
21567
21686
  }
@@ -21588,11 +21707,11 @@ var DEFAULT_BOT_NAMES = /* @__PURE__ */ new Set(["Bot", "Workspace Agent"]);
21588
21707
  async function syncPersonaAvatars(profile, requested) {
21589
21708
  const root = cafeRoot();
21590
21709
  const character = requested || configuredCharacter(root);
21591
- const dir = join8(root, "characters", character, "avatars");
21592
- if (!existsSync9(dir)) installPack(root, character);
21710
+ const dir = join6(root, "characters", character, "avatars");
21711
+ if (!existsSync8(dir)) installPack(root, character);
21593
21712
  const avatars = {};
21594
21713
  for (const file of readdirSync2(dir).filter((f) => f.endsWith(".webp"))) {
21595
- const image = await sharp(join8(dir, file)).resize({ width: AVATAR_SIZE, height: AVATAR_SIZE, fit: "cover", position: "top" }).webp({ quality: 80 }).toBuffer();
21714
+ const image = await sharp(join6(dir, file)).resize({ width: AVATAR_SIZE, height: AVATAR_SIZE, fit: "cover", position: "top" }).webp({ quality: 80 }).toBuffer();
21596
21715
  avatars[basename2(file, ".webp")] = `data:image/webp;base64,${image.toString("base64")}`;
21597
21716
  }
21598
21717
  if (!Object.keys(avatars).length) throw new Error(`No .webp avatars in ${dir}.`);
@@ -21610,14 +21729,14 @@ async function autoSyncPersonaAvatars(profile) {
21610
21729
  const root = cafeRoot();
21611
21730
  const character = configuredCharacter(root);
21612
21731
  const stamp = `${character}@${PACKS[character]?.version ?? "local"}`;
21613
- const marker = join8(root, `.flyspace-avatars-${profile}`);
21732
+ const marker = join6(root, `.flyspace-avatars-${profile}`);
21614
21733
  try {
21615
- if (readFileSync6(marker, "utf8") === stamp) return;
21734
+ if (readFileSync4(marker, "utf8") === stamp) return;
21616
21735
  } catch {
21617
21736
  }
21618
21737
  try {
21619
21738
  const { count } = await syncPersonaAvatars(profile, character);
21620
- writeFileSync5(marker, stamp);
21739
+ writeFileSync3(marker, stamp);
21621
21740
  console.log(`[persona] synced ${count} ${character} avatars`);
21622
21741
  } catch (err) {
21623
21742
  console.warn(`[persona] avatar sync skipped: ${err.message}`);
@@ -22074,24 +22193,24 @@ async function loadAgentMemory(profile, channelId, opts = {}) {
22074
22193
  async function buildPrompt(profile, channelId, opts) {
22075
22194
  const workspace = await getWorkspaceBySlug(profile);
22076
22195
  const handle = opts.senderHandle?.toLowerCase();
22077
- const sender2 = workspace && handle ? (await listMemberships(workspace.id)).find(
22196
+ const sender = workspace && handle ? (await listMemberships(workspace.id)).find(
22078
22197
  (m) => m.userId && m.handle.toLowerCase() === handle
22079
22198
  ) : void 0;
22080
22199
  const [channel, shared, own] = await Promise.all([
22081
22200
  listMemories({ scope: "channel", channelId }),
22082
22201
  workspace ? listMemories({ scope: "workspace", workspaceId: workspace.id }) : [],
22083
- workspace && sender2 ? listMemories({ scope: "user", workspaceId: workspace.id, userId: sender2.userId }) : []
22202
+ workspace && sender ? listMemories({ scope: "user", workspaceId: workspace.id, userId: sender.userId }) : []
22084
22203
  ]);
22085
22204
  const extras = {
22086
22205
  workspace: shared,
22087
- ...sender2 ? { user: { userId: sender2.userId, handle: sender2.handle, memories: own } } : {}
22206
+ ...sender ? { user: { userId: sender.userId, handle: sender.handle, memories: own } } : {}
22088
22207
  };
22089
22208
  return formatMemoryPrompt(channelId, channel, extras);
22090
22209
  }
22091
22210
 
22092
22211
  // src/dashboard/settings-host.ts
22093
- import { writeFileSync as writeFileSync6, existsSync as existsSync10, mkdirSync as mkdirSync7, readFileSync as readFileSync7, rmSync as rmSync6 } from "fs";
22094
- import { dirname as dirname2 } from "path";
22212
+ import { writeFileSync as writeFileSync4, existsSync as existsSync9, mkdirSync as mkdirSync6, readFileSync as readFileSync5, rmSync as rmSync4 } from "fs";
22213
+ import { dirname } from "path";
22095
22214
 
22096
22215
  // ../api/src/dashboard/auto-title.ts
22097
22216
  var GROQ_API_URL = "https://api.groq.com/openai/v1/chat/completions";
@@ -22252,9 +22371,9 @@ function parseAgentProfiles(raw) {
22252
22371
  return entries2.length > 0 ? Object.fromEntries(entries2) : void 0;
22253
22372
  }
22254
22373
  function loadDashboardSettings() {
22255
- if (!existsSync10(paths.DASHBOARD_SETTINGS_FILE)) return localDefaults();
22374
+ if (!existsSync9(paths.DASHBOARD_SETTINGS_FILE)) return localDefaults();
22256
22375
  try {
22257
- const raw = JSON.parse(readFileSync7(paths.DASHBOARD_SETTINGS_FILE, "utf-8"));
22376
+ const raw = JSON.parse(readFileSync5(paths.DASHBOARD_SETTINGS_FILE, "utf-8"));
22258
22377
  const providers = parseProviders(raw.providers, {
22259
22378
  agent: normalizeDefaultModel(raw.agent, localDefaults().agent),
22260
22379
  fallbackModel: typeof raw.fallbackModel === "string" && isAllowedModel(raw.fallbackModel) ? raw.fallbackModel : void 0
@@ -22281,9 +22400,9 @@ function withFallbackModel(providers, model) {
22281
22400
  return [cleared[0], { runner, model }, ...cleared.slice(1).filter((p) => p.runner !== runner)];
22282
22401
  }
22283
22402
  function writeSettings(next) {
22284
- mkdirSync7(dirname2(paths.DASHBOARD_SETTINGS_FILE), { recursive: true });
22403
+ mkdirSync6(dirname(paths.DASHBOARD_SETTINGS_FILE), { recursive: true });
22285
22404
  const merged = { ...readSettingsFile() ?? {}, ...next };
22286
- writeFileSync6(paths.DASHBOARD_SETTINGS_FILE, JSON.stringify(merged, null, 2), "utf-8");
22405
+ writeFileSync4(paths.DASHBOARD_SETTINGS_FILE, JSON.stringify(merged, null, 2), "utf-8");
22287
22406
  return next;
22288
22407
  }
22289
22408
  function saveDashboardSettings(patch) {
@@ -22317,13 +22436,13 @@ async function loadFullDashboardSettings(profile = getProfile()) {
22317
22436
  function saveWorkspacePrompt(prompt) {
22318
22437
  const trimmed = prompt.trim();
22319
22438
  if (!trimmed || trimmed === loadWorkspacePrompt().defaultPrompt) return resetWorkspacePrompt();
22320
- mkdirSync7(dirname2(paths.PROMPT_FILE), { recursive: true });
22321
- writeFileSync6(paths.PROMPT_FILE, `${trimmed}
22439
+ mkdirSync6(dirname(paths.PROMPT_FILE), { recursive: true });
22440
+ writeFileSync4(paths.PROMPT_FILE, `${trimmed}
22322
22441
  `, "utf-8");
22323
22442
  return loadWorkspacePrompt();
22324
22443
  }
22325
22444
  function resetWorkspacePrompt() {
22326
- rmSync6(paths.PROMPT_FILE, { force: true });
22445
+ rmSync4(paths.PROMPT_FILE, { force: true });
22327
22446
  return loadWorkspacePrompt();
22328
22447
  }
22329
22448
  function saveAgentProfile(name, patch) {
@@ -22348,9 +22467,9 @@ function saveAgentProfile(name, patch) {
22348
22467
 
22349
22468
  // ../api/src/codex/agent.ts
22350
22469
  import { spawn as spawn2 } from "child_process";
22351
- import { existsSync as existsSync11, mkdtempSync as mkdtempSync3, readFileSync as readFileSync8, rmSync as rmSync7, statSync as statSync3 } from "fs";
22470
+ import { existsSync as existsSync10, mkdtempSync as mkdtempSync3, readFileSync as readFileSync6, rmSync as rmSync5, statSync as statSync4 } from "fs";
22352
22471
  import { tmpdir as tmpdir2 } from "os";
22353
- import { join as join9 } from "path";
22472
+ import { join as join7 } from "path";
22354
22473
  var AUTH_ERROR_PATTERNS2 = [
22355
22474
  /401 unauthorized/i,
22356
22475
  /missing bearer or basic authentication/i,
@@ -22481,8 +22600,8 @@ function getMaxDurationMs2() {
22481
22600
  }
22482
22601
  function codexAuthAvailable(env = process.env) {
22483
22602
  if (env["OPENAI_API_KEY"]?.trim()) return true;
22484
- const home = env["CODEX_HOME"]?.trim() || join9(env["HOME"] ?? "", ".codex");
22485
- return existsSync11(join9(home, "auth.json"));
22603
+ const home = env["CODEX_HOME"]?.trim() || join7(env["HOME"] ?? "", ".codex");
22604
+ return existsSync10(join7(home, "auth.json"));
22486
22605
  }
22487
22606
  function applySystemPrompt(prompt, options, resumeSessionId) {
22488
22607
  if (resumeSessionId || !options.systemPrompt?.trim()) return prompt;
@@ -22536,8 +22655,8 @@ function runCodexCli(prompt, cwd, options, resumeSessionId) {
22536
22655
  recordCodexUsage(response, options);
22537
22656
  resolve8(response);
22538
22657
  };
22539
- const scratch = mkdtempSync3(join9(tmpdir2(), "flyspace-codex-"));
22540
- const lastMessageFile = join9(scratch, "last-message.txt");
22658
+ const scratch = mkdtempSync3(join7(tmpdir2(), "flyspace-codex-"));
22659
+ const lastMessageFile = join7(scratch, "last-message.txt");
22541
22660
  const args = buildArgs2(prompt, options, lastMessageFile, resumeSessionId);
22542
22661
  console.log(`[codex] spawning codex CLI in ${cwd}`);
22543
22662
  console.log(`[codex] args: ${args.slice(0, -1).join(" ")}`);
@@ -22550,7 +22669,7 @@ function runCodexCli(prompt, cwd, options, resumeSessionId) {
22550
22669
  let stderr = "";
22551
22670
  let timedOut = false;
22552
22671
  let cancelled = false;
22553
- let pending2 = "";
22672
+ let pending = "";
22554
22673
  const seenItemIds = /* @__PURE__ */ new Set();
22555
22674
  const onActivity = options.onActivity;
22556
22675
  const consumeLine = (raw) => {
@@ -22607,7 +22726,7 @@ function runCodexCli(prompt, cwd, options, resumeSessionId) {
22607
22726
  const cleanup = () => {
22608
22727
  clearTimeout(timeoutHandle);
22609
22728
  if (signal) signal.removeEventListener("abort", onAbort);
22610
- rmSync7(scratch, { recursive: true, force: true });
22729
+ rmSync5(scratch, { recursive: true, force: true });
22611
22730
  };
22612
22731
  child.stdout.setEncoding("utf8");
22613
22732
  child.stderr.setEncoding("utf8");
@@ -22615,9 +22734,9 @@ function runCodexCli(prompt, cwd, options, resumeSessionId) {
22615
22734
  const chunk = data.toString();
22616
22735
  stdout += chunk;
22617
22736
  if (!onActivity) return;
22618
- pending2 += chunk;
22619
- const lines = pending2.split("\n");
22620
- pending2 = lines.pop() ?? "";
22737
+ pending += chunk;
22738
+ const lines = pending.split("\n");
22739
+ pending = lines.pop() ?? "";
22621
22740
  for (const line of lines) consumeLine(line);
22622
22741
  });
22623
22742
  child.stderr.on("data", (data) => {
@@ -22636,7 +22755,7 @@ function runCodexCli(prompt, cwd, options, resumeSessionId) {
22636
22755
  child.on("close", (code, signal2) => {
22637
22756
  let lastMessage = "";
22638
22757
  try {
22639
- lastMessage = readFileSync8(lastMessageFile, "utf8").trim();
22758
+ lastMessage = readFileSync6(lastMessageFile, "utf8").trim();
22640
22759
  } catch {
22641
22760
  lastMessage = "";
22642
22761
  }
@@ -22690,7 +22809,7 @@ function runCodexCli(prompt, cwd, options, resumeSessionId) {
22690
22809
  });
22691
22810
  }
22692
22811
  async function askCodex(prompt, cwd, options = {}, resumeSessionId) {
22693
- if (!existsSync11(cwd) || !statSync3(cwd).isDirectory()) {
22812
+ if (!existsSync10(cwd) || !statSync4(cwd).isDirectory()) {
22694
22813
  console.error(`[codex] working directory does not exist: ${cwd}`);
22695
22814
  return {
22696
22815
  sessionId: resumeSessionId ?? "",
@@ -22951,11 +23070,11 @@ function walkBlock(token, out) {
22951
23070
  }
22952
23071
  function walkList(list, indent, out) {
22953
23072
  const style = list.ordered ? "ordered" : "bullet";
22954
- let pending2 = [];
23073
+ let pending = [];
22955
23074
  const flush2 = () => {
22956
- if (pending2.length > 0) {
22957
- out.push({ type: "rich_text_list", style, indent, elements: pending2 });
22958
- pending2 = [];
23075
+ if (pending.length > 0) {
23076
+ out.push({ type: "rich_text_list", style, indent, elements: pending });
23077
+ pending = [];
22959
23078
  }
22960
23079
  };
22961
23080
  for (const item of list.items) {
@@ -22979,7 +23098,7 @@ function walkList(list, indent, out) {
22979
23098
  }
22980
23099
  }
22981
23100
  }
22982
- pending2.push({
23101
+ pending.push({
22983
23102
  type: "rich_text_section",
22984
23103
  elements: inline.length > 0 ? mergeAdjacentText(inline) : [{ type: "text", text: "" }]
22985
23104
  });
@@ -23138,12 +23257,12 @@ function renderAsciiTable(t) {
23138
23257
  (h, i) => Math.max(h.length, ...rows2.map((r) => (r[i] || "").length))
23139
23258
  );
23140
23259
  const fmt = (cells) => "| " + cells.map((c, i) => c.padEnd(widths[i])).join(" | ") + " |";
23141
- const sep4 = "|" + widths.map((w) => "-".repeat(w + 2)).join("|") + "|";
23142
- return [fmt(headers), sep4, ...rows2.map(fmt)].join("\n");
23260
+ const sep5 = "|" + widths.map((w) => "-".repeat(w + 2)).join("|") + "|";
23261
+ return [fmt(headers), sep5, ...rows2.map(fmt)].join("\n");
23143
23262
  }
23144
23263
 
23145
23264
  // src/store/channel-cache.ts
23146
- import { mkdirSync as mkdirSync8 } from "fs";
23265
+ import { mkdirSync as mkdirSync7 } from "fs";
23147
23266
 
23148
23267
  // src/store/sqlite.ts
23149
23268
  import Database from "better-sqlite3";
@@ -23167,7 +23286,7 @@ function getDb() {
23167
23286
  const file = paths.DB_FILE;
23168
23287
  const existing = dbs.get(file);
23169
23288
  if (existing) return existing;
23170
- mkdirSync8(paths.DATA_DIR, { recursive: true });
23289
+ mkdirSync7(paths.DATA_DIR, { recursive: true });
23171
23290
  const db = openLocalDatabase(file);
23172
23291
  if (!db) return null;
23173
23292
  db.exec(`
@@ -23683,17 +23802,17 @@ var TriggerEngine = class {
23683
23802
  };
23684
23803
 
23685
23804
  // src/store/user-cache.ts
23686
- import { existsSync as existsSync12, readFileSync as readFileSync9 } from "fs";
23687
- import { join as join10 } from "path";
23805
+ import { existsSync as existsSync11, readFileSync as readFileSync7 } from "fs";
23806
+ import { join as join8 } from "path";
23688
23807
  function jsonUserCachePath() {
23689
- const file = join10(paths.CONFIG_DIR, "slack_users.json");
23690
- return existsSync12(file) ? file : void 0;
23808
+ const file = join8(paths.CONFIG_DIR, "slack_users.json");
23809
+ return existsSync11(file) ? file : void 0;
23691
23810
  }
23692
23811
  function readJsonUserCache() {
23693
23812
  const file = jsonUserCachePath();
23694
23813
  if (!file) return void 0;
23695
23814
  try {
23696
- const parsed = JSON.parse(readFileSync9(file, "utf8"));
23815
+ const parsed = JSON.parse(readFileSync7(file, "utf8"));
23697
23816
  return parsed.users;
23698
23817
  } catch {
23699
23818
  return void 0;
@@ -24100,7 +24219,7 @@ var MessageQueue = class {
24100
24219
 
24101
24220
  // src/slack/file-downloader.ts
24102
24221
  import { writeFile } from "fs/promises";
24103
- import { join as join11, extname } from "path";
24222
+ import { join as join9, extname } from "path";
24104
24223
  var debug3 = process.env["DEBUG"] === "true";
24105
24224
  var SUPPORTED_IMAGE_MIMETYPES = /* @__PURE__ */ new Set([
24106
24225
  "image/png",
@@ -24200,7 +24319,7 @@ async function downloadOne(file, botToken) {
24200
24319
  const ext = extname(originalName) || `.${file.filetype ?? "bin"}`;
24201
24320
  const safeName = sanitizeFilename(originalName.replace(ext, ""));
24202
24321
  const filename = `${Date.now()}-${file.id ?? "unnamed"}-${safeName}${ext}`;
24203
- const localPath = join11(paths.UPLOADS_DIR, filename);
24322
+ const localPath = join9(paths.UPLOADS_DIR, filename);
24204
24323
  await writeFile(localPath, buffer);
24205
24324
  if (debug3)
24206
24325
  console.log(`[file-downloader] saved ${file.id} -> ${localPath} (${buffer.length} bytes)`);
@@ -24648,16 +24767,16 @@ async function summariseThreadTranscript(transcript, opts, deps = {}) {
24648
24767
  }
24649
24768
 
24650
24769
  // src/dashboard/chat-agent.ts
24651
- import { homedir as homedir8 } from "os";
24770
+ import { homedir as homedir9 } from "os";
24652
24771
  import { stripVTControlCharacters } from "util";
24653
24772
 
24654
24773
  // src/mcp/config.ts
24655
- import { mkdtempSync as mkdtempSync4, rmSync as rmSync8, writeFileSync as writeFileSync7 } from "fs";
24774
+ import { mkdtempSync as mkdtempSync4, rmSync as rmSync6, writeFileSync as writeFileSync5 } from "fs";
24656
24775
  import { tmpdir as tmpdir3 } from "os";
24657
- import { join as join12 } from "path";
24776
+ import { join as join10 } from "path";
24658
24777
 
24659
24778
  // ../api/src/mcp/crypto.ts
24660
- import { createCipheriv, createDecipheriv, randomBytes as randomBytes2, timingSafeEqual } from "crypto";
24779
+ import { createCipheriv, createDecipheriv, randomBytes, timingSafeEqual } from "crypto";
24661
24780
  var ALGORITHM = "aes-256-gcm";
24662
24781
  var KEY_BYTES = 32;
24663
24782
  var IV_BYTES = 12;
@@ -24690,7 +24809,7 @@ function currentKeyVersion() {
24690
24809
  );
24691
24810
  }
24692
24811
  function encrypt(key, purpose, plaintext) {
24693
- const iv = randomBytes2(IV_BYTES);
24812
+ const iv = randomBytes(IV_BYTES);
24694
24813
  const cipher = createCipheriv(ALGORITHM, key, iv);
24695
24814
  cipher.setAAD(Buffer.from(purpose, "utf8"));
24696
24815
  const ciphertext = Buffer.concat([cipher.update(plaintext, "utf8"), cipher.final()]);
@@ -24710,7 +24829,7 @@ function decrypt(key, purpose, blob) {
24710
24829
  }
24711
24830
  function createEnvelope() {
24712
24831
  const keyVersion = currentKeyVersion();
24713
- const key = randomBytes2(KEY_BYTES);
24832
+ const key = randomBytes(KEY_BYTES);
24714
24833
  const wrappedDek = encrypt(
24715
24834
  readMasterKey(keyVersion),
24716
24835
  purposeForDek(keyVersion),
@@ -24776,7 +24895,7 @@ function secretsMatch(a, b) {
24776
24895
  }
24777
24896
 
24778
24897
  // ../api/src/mcp/oauth.ts
24779
- import { createHash as createHash4, randomBytes as randomBytes3 } from "crypto";
24898
+ import { createHash as createHash5, randomBytes as randomBytes2 } from "crypto";
24780
24899
  var RESERVED_AUTHORIZE_PARAMS = /* @__PURE__ */ new Set([
24781
24900
  "client_id",
24782
24901
  "redirect_uri",
@@ -24790,11 +24909,11 @@ function base64url(buffer) {
24790
24909
  return buffer.toString("base64").replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
24791
24910
  }
24792
24911
  function createStateToken() {
24793
- return base64url(randomBytes3(32));
24912
+ return base64url(randomBytes2(32));
24794
24913
  }
24795
24914
  function createPkcePair() {
24796
- const verifier = base64url(randomBytes3(32));
24797
- const challenge = base64url(createHash4("sha256").update(verifier).digest());
24915
+ const verifier = base64url(randomBytes2(32));
24916
+ const challenge = base64url(createHash5("sha256").update(verifier).digest());
24798
24917
  return { verifier, challenge };
24799
24918
  }
24800
24919
  function clientEnvName(providerSlug, suffix) {
@@ -24914,7 +25033,7 @@ async function exchangeCode(params) {
24914
25033
  );
24915
25034
  return { ...tokens, scopes: tokens.scopes.length ? tokens.scopes : provider.defaultScopes };
24916
25035
  }
24917
- async function refreshAccessToken2(params) {
25036
+ async function refreshAccessToken(params) {
24918
25037
  const { provider, client, refreshToken } = params;
24919
25038
  return requestToken(
24920
25039
  provider,
@@ -25200,7 +25319,7 @@ async function renew(workspaceId, connection, provider, deps) {
25200
25319
  }
25201
25320
  let tokens;
25202
25321
  try {
25203
- tokens = await refreshAccessToken2({
25322
+ tokens = await refreshAccessToken({
25204
25323
  provider,
25205
25324
  client: readOAuthClient(provider.slug),
25206
25325
  refreshToken,
@@ -25290,12 +25409,12 @@ async function buildMcpConfig(profile, connectionIds) {
25290
25409
  if (!connectionIds.length) return { config, skipped };
25291
25410
  const workspace = await getWorkspaceBySlug(profile);
25292
25411
  if (!workspace) return { config, skipped };
25293
- const byId = new Map(
25412
+ const byId2 = new Map(
25294
25413
  (await listMcpConnections(workspace.id)).map((connection) => [connection.id, connection])
25295
25414
  );
25296
25415
  const workspaceId = workspace.id;
25297
25416
  for (const id of connectionIds) {
25298
- const connection = byId.get(id);
25417
+ const connection = byId2.get(id);
25299
25418
  if (!connection) {
25300
25419
  continue;
25301
25420
  }
@@ -25340,12 +25459,12 @@ async function buildMcpConfig(profile, connectionIds) {
25340
25459
  return { config, skipped };
25341
25460
  }
25342
25461
  function writeMcpConfigFile(config) {
25343
- const dir = mkdtempSync4(join12(tmpdir3(), "flyspace-mcp-"));
25344
- const path = join12(dir, "mcp-config.json");
25345
- writeFileSync7(path, JSON.stringify(config), { mode: 384 });
25462
+ const dir = mkdtempSync4(join10(tmpdir3(), "flyspace-mcp-"));
25463
+ const path = join10(dir, "mcp-config.json");
25464
+ writeFileSync5(path, JSON.stringify(config), { mode: 384 });
25346
25465
  return {
25347
25466
  path,
25348
- cleanup: () => rmSync8(dir, { recursive: true, force: true })
25467
+ cleanup: () => rmSync6(dir, { recursive: true, force: true })
25349
25468
  };
25350
25469
  }
25351
25470
  async function withMcpConfig(profile, connectionIds, fn, extraServers = {}) {
@@ -25363,8 +25482,8 @@ async function withMcpConfig(profile, connectionIds, fn, extraServers = {}) {
25363
25482
  }
25364
25483
 
25365
25484
  // ../api/src/version.ts
25366
- import { readFileSync as readFileSync10 } from "fs";
25367
- var CLI_VERSION = true ? "0.1.59" : devVersion();
25485
+ import { readFileSync as readFileSync8 } from "fs";
25486
+ var CLI_VERSION = true ? "0.1.61" : devVersion();
25368
25487
  function isOlderVersion(a, b) {
25369
25488
  const parse2 = (v) => v.replace(/^v/, "").split("-")[0].split(".").map(Number);
25370
25489
  const [pa, pb] = [parse2(a), parse2(b)];
@@ -25372,7 +25491,7 @@ function isOlderVersion(a, b) {
25372
25491
  for (let i = 0; i < 3; i++) if (pa[i] !== pb[i]) return pa[i] < pb[i];
25373
25492
  return false;
25374
25493
  }
25375
- var LATEST_TTL_MS = 60 * 6e4;
25494
+ var LATEST_TTL_MS = 5 * 6e4;
25376
25495
  var latest = null;
25377
25496
  async function latestCliVersion() {
25378
25497
  if (latest && Date.now() - latest.at < LATEST_TTL_MS) return latest.version;
@@ -25387,42 +25506,42 @@ async function latestCliVersion() {
25387
25506
  }
25388
25507
 
25389
25508
  // src/claude/agents.ts
25390
- import { existsSync as existsSync15, readdirSync as readdirSync5, readFileSync as readFileSync13 } from "fs";
25391
- import { homedir as homedir6 } from "os";
25392
- import { basename as basename4, join as join15 } from "path";
25509
+ import { existsSync as existsSync14, readdirSync as readdirSync5, readFileSync as readFileSync11 } from "fs";
25510
+ import { homedir as homedir7 } from "os";
25511
+ import { basename as basename4, join as join13 } from "path";
25393
25512
  import yaml3 from "js-yaml";
25394
25513
 
25395
25514
  // ../api/src/claude/skills.ts
25396
- import { existsSync as existsSync14, readdirSync as readdirSync4, readFileSync as readFileSync12, statSync as statSync5 } from "fs";
25397
- import { homedir as homedir5 } from "os";
25398
- import { basename as basename3, dirname as dirname3, join as join14 } from "path";
25515
+ import { existsSync as existsSync13, readdirSync as readdirSync4, readFileSync as readFileSync10, statSync as statSync6 } from "fs";
25516
+ import { homedir as homedir6 } from "os";
25517
+ import { basename as basename3, dirname as dirname2, join as join12 } from "path";
25399
25518
  import yaml2 from "js-yaml";
25400
25519
 
25401
25520
  // ../api/src/claude/skill-files.ts
25402
25521
  import {
25403
- existsSync as existsSync13,
25404
- mkdirSync as mkdirSync9,
25405
- readFileSync as readFileSync11,
25522
+ existsSync as existsSync12,
25523
+ mkdirSync as mkdirSync8,
25524
+ readFileSync as readFileSync9,
25406
25525
  readdirSync as readdirSync3,
25407
- rmSync as rmSync9,
25408
- statSync as statSync4,
25409
- writeFileSync as writeFileSync8
25526
+ rmSync as rmSync7,
25527
+ statSync as statSync5,
25528
+ writeFileSync as writeFileSync6
25410
25529
  } from "fs";
25411
- import { homedir as homedir4 } from "os";
25412
- import { join as join13, resolve as resolve5, sep as sep2 } from "path";
25530
+ import { homedir as homedir5 } from "os";
25531
+ import { join as join11, resolve as resolve5, sep as sep3 } from "path";
25413
25532
  import yaml from "js-yaml";
25414
25533
  var MAX_SKILL_BYTES = 2 * 1024 * 1024;
25415
25534
  var SKILL_NAME = /^[a-z0-9](?:[a-z0-9-]{0,62}[a-z0-9])?$/;
25416
25535
  function expandHome(p) {
25417
- if (p === "~") return homedir4();
25418
- if (p.startsWith("~/")) return join13(homedir4(), p.slice(2));
25536
+ if (p === "~") return homedir5();
25537
+ if (p.startsWith("~/")) return join11(homedir5(), p.slice(2));
25419
25538
  return p;
25420
25539
  }
25421
25540
  function workspaceSkillsDir(configDir) {
25422
- return join13(configDir ? expandHome(configDir) : join13(homedir4(), ".claude"), "skills");
25541
+ return join11(configDir ? expandHome(configDir) : join11(homedir5(), ".claude"), "skills");
25423
25542
  }
25424
25543
  function channelSkillsDir(cwd) {
25425
- return join13(cwd, ".claude", "skills");
25544
+ return join11(cwd, ".claude", "skills");
25426
25545
  }
25427
25546
  function isValidSkillName(name) {
25428
25547
  return SKILL_NAME.test(name);
@@ -25430,7 +25549,7 @@ function isValidSkillName(name) {
25430
25549
  function resolveSkillPath(dir, name) {
25431
25550
  if (!isValidSkillName(name)) return null;
25432
25551
  const abs = resolve5(dir, name, "SKILL.md");
25433
- if (!abs.startsWith(resolve5(dir) + sep2)) return null;
25552
+ if (!abs.startsWith(resolve5(dir) + sep3)) return null;
25434
25553
  return abs;
25435
25554
  }
25436
25555
  function splitFrontmatter(raw) {
@@ -25457,7 +25576,7 @@ ${body.replace(/^\n+/, "").trimEnd()}
25457
25576
  }
25458
25577
  function readMeta(abs) {
25459
25578
  try {
25460
- const { fm } = splitFrontmatter(readFileSync11(abs, "utf-8"));
25579
+ const { fm } = splitFrontmatter(readFileSync9(abs, "utf-8"));
25461
25580
  return {
25462
25581
  name: typeof fm["name"] === "string" ? fm["name"] : void 0,
25463
25582
  description: typeof fm["description"] === "string" ? fm["description"] : void 0
@@ -25467,7 +25586,7 @@ function readMeta(abs) {
25467
25586
  }
25468
25587
  }
25469
25588
  function listSkillFiles(dir) {
25470
- if (!existsSync13(dir)) return [];
25589
+ if (!existsSync12(dir)) return [];
25471
25590
  let entries2;
25472
25591
  try {
25473
25592
  entries2 = readdirSync3(dir);
@@ -25477,10 +25596,10 @@ function listSkillFiles(dir) {
25477
25596
  const rows2 = [];
25478
25597
  for (const entry of entries2) {
25479
25598
  if (!isValidSkillName(entry)) continue;
25480
- const abs = join13(dir, entry, "SKILL.md");
25599
+ const abs = join11(dir, entry, "SKILL.md");
25481
25600
  let stat;
25482
25601
  try {
25483
- stat = statSync4(abs);
25602
+ stat = statSync5(abs);
25484
25603
  } catch {
25485
25604
  continue;
25486
25605
  }
@@ -25501,12 +25620,12 @@ function readSkillFile(dir, name) {
25501
25620
  if (!abs) return null;
25502
25621
  let stat;
25503
25622
  try {
25504
- stat = statSync4(abs);
25623
+ stat = statSync5(abs);
25505
25624
  } catch {
25506
25625
  return null;
25507
25626
  }
25508
25627
  if (!stat.isFile() || stat.size > MAX_SKILL_BYTES) return null;
25509
- const { fm, body } = splitFrontmatter(readFileSync11(abs, "utf-8"));
25628
+ const { fm, body } = splitFrontmatter(readFileSync9(abs, "utf-8"));
25510
25629
  return {
25511
25630
  name,
25512
25631
  description: typeof fm["description"] === "string" ? fm["description"].trim() : "",
@@ -25520,7 +25639,7 @@ function writeSkillFile(dir, name, patch, baseMtime) {
25520
25639
  if (!abs) return { status: "not-found" };
25521
25640
  let stat;
25522
25641
  try {
25523
- stat = statSync4(abs);
25642
+ stat = statSync5(abs);
25524
25643
  } catch {
25525
25644
  return { status: "not-found" };
25526
25645
  }
@@ -25528,18 +25647,18 @@ function writeSkillFile(dir, name, patch, baseMtime) {
25528
25647
  if (baseMtime && stat.mtime.toISOString() !== baseMtime) {
25529
25648
  return { status: "conflict", mtime: stat.mtime.toISOString() };
25530
25649
  }
25531
- const { fm } = splitFrontmatter(readFileSync11(abs, "utf-8"));
25650
+ const { fm } = splitFrontmatter(readFileSync9(abs, "utf-8"));
25532
25651
  const content = buildSkillFile({ ...fm, name, description: patch.description }, patch.body);
25533
25652
  if (Buffer.byteLength(content, "utf8") > MAX_SKILL_BYTES) return { status: "too-large" };
25534
- writeFileSync8(abs, content, "utf8");
25535
- return { status: "ok", mtime: statSync4(abs).mtime.toISOString() };
25653
+ writeFileSync6(abs, content, "utf8");
25654
+ return { status: "ok", mtime: statSync5(abs).mtime.toISOString() };
25536
25655
  }
25537
25656
  function createSkillFile(dir, name, description) {
25538
25657
  const abs = resolveSkillPath(dir, name);
25539
25658
  if (!abs) return { status: "bad-name" };
25540
- if (existsSync13(abs)) return { status: "exists" };
25541
- mkdirSync9(join13(dir, name), { recursive: true });
25542
- writeFileSync8(
25659
+ if (existsSync12(abs)) return { status: "exists" };
25660
+ mkdirSync8(join11(dir, name), { recursive: true });
25661
+ writeFileSync6(
25543
25662
  abs,
25544
25663
  buildSkillFile(
25545
25664
  { name, description },
@@ -25555,24 +25674,24 @@ Describe what this skill does and when to use it.
25555
25674
  }
25556
25675
  function deleteSkillFile(dir, name) {
25557
25676
  const abs = resolveSkillPath(dir, name);
25558
- if (!abs || !existsSync13(abs)) return { status: "not-found" };
25559
- rmSync9(join13(dir, name), { recursive: true, force: true });
25677
+ if (!abs || !existsSync12(abs)) return { status: "not-found" };
25678
+ rmSync7(join11(dir, name), { recursive: true, force: true });
25560
25679
  return { status: "ok" };
25561
25680
  }
25562
25681
 
25563
25682
  // ../api/src/claude/skills.ts
25564
25683
  function defaultConfigDir() {
25565
- return join14(homedir5(), ".claude");
25684
+ return join12(homedir6(), ".claude");
25566
25685
  }
25567
25686
  function expandHome2(p) {
25568
- if (p === "~") return homedir5();
25569
- if (p.startsWith("~/")) return join14(homedir5(), p.slice(2));
25687
+ if (p === "~") return homedir6();
25688
+ if (p.startsWith("~/")) return join12(homedir6(), p.slice(2));
25570
25689
  return p;
25571
25690
  }
25572
25691
  function parseFrontmatter(file) {
25573
25692
  let content;
25574
25693
  try {
25575
- content = readFileSync12(file, "utf-8");
25694
+ content = readFileSync10(file, "utf-8");
25576
25695
  } catch {
25577
25696
  return {};
25578
25697
  }
@@ -25590,13 +25709,13 @@ function parseFrontmatter(file) {
25590
25709
  function isSymlinkedDir(root, entry) {
25591
25710
  if (!entry.isSymbolicLink()) return false;
25592
25711
  try {
25593
- return statSync5(join14(root, entry.name)).isDirectory();
25712
+ return statSync6(join12(root, entry.name)).isDirectory();
25594
25713
  } catch {
25595
25714
  return false;
25596
25715
  }
25597
25716
  }
25598
25717
  function findSkillFiles(root, maxDepth, out) {
25599
- if (maxDepth < 0 || !existsSync14(root)) return;
25718
+ if (maxDepth < 0 || !existsSync13(root)) return;
25600
25719
  let entries2;
25601
25720
  try {
25602
25721
  entries2 = readdirSync4(root, { withFileTypes: true });
@@ -25605,24 +25724,24 @@ function findSkillFiles(root, maxDepth, out) {
25605
25724
  }
25606
25725
  for (const entry of entries2) {
25607
25726
  if (entry.isFile()) {
25608
- if (entry.name === "SKILL.md") out.push(join14(root, entry.name));
25727
+ if (entry.name === "SKILL.md") out.push(join12(root, entry.name));
25609
25728
  } else if (entry.isDirectory() || isSymlinkedDir(root, entry)) {
25610
25729
  if (entry.name === "node_modules" || entry.name.startsWith(".")) continue;
25611
- findSkillFiles(join14(root, entry.name), maxDepth - 1, out);
25730
+ findSkillFiles(join12(root, entry.name), maxDepth - 1, out);
25612
25731
  }
25613
25732
  }
25614
25733
  }
25615
25734
  function pluginNameFor(file, root) {
25616
- let dir = dirname3(file);
25617
- while (dir.startsWith(root) && dir !== dirname3(dir)) {
25735
+ let dir = dirname2(file);
25736
+ while (dir.startsWith(root) && dir !== dirname2(dir)) {
25618
25737
  try {
25619
25738
  const manifest = JSON.parse(
25620
- readFileSync12(join14(dir, ".claude-plugin", "plugin.json"), "utf-8")
25739
+ readFileSync10(join12(dir, ".claude-plugin", "plugin.json"), "utf-8")
25621
25740
  );
25622
25741
  if (typeof manifest.name === "string" && manifest.name.trim()) return manifest.name.trim();
25623
25742
  } catch {
25624
25743
  }
25625
- dir = dirname3(dir);
25744
+ dir = dirname2(dir);
25626
25745
  }
25627
25746
  return void 0;
25628
25747
  }
@@ -25639,17 +25758,17 @@ function findPluginMarkdown(pluginsRoot, dirName, maxDepth = 8) {
25639
25758
  for (const entry of entries2) {
25640
25759
  if (entry.name === "node_modules" || entry.name.startsWith(".")) continue;
25641
25760
  if (!entry.isDirectory() && !isSymlinkedDir(dir, entry)) continue;
25642
- const child = join14(dir, entry.name);
25761
+ const child = join12(dir, entry.name);
25643
25762
  if (entry.name === dirName) {
25644
25763
  for (const f of readdirSafe(child)) {
25645
- if (f.endsWith(".md")) out.push({ file: join14(child, f), plugin: pluginNameFor(join14(child, f), pluginsRoot) });
25764
+ if (f.endsWith(".md")) out.push({ file: join12(child, f), plugin: pluginNameFor(join12(child, f), pluginsRoot) });
25646
25765
  }
25647
25766
  } else {
25648
25767
  walk(child, depth - 1);
25649
25768
  }
25650
25769
  }
25651
25770
  };
25652
- if (existsSync14(pluginsRoot)) walk(pluginsRoot, maxDepth);
25771
+ if (existsSync13(pluginsRoot)) walk(pluginsRoot, maxDepth);
25653
25772
  return out;
25654
25773
  }
25655
25774
  function readdirSafe(dir) {
@@ -25663,14 +25782,14 @@ function listCommands(configDir, cwd) {
25663
25782
  const base = configDir ? expandHome2(configDir) : defaultConfigDir();
25664
25783
  const local = (dir, source) => readdirSafe(dir).filter((f) => f.endsWith(".md")).map((f) => ({
25665
25784
  name: basename3(f, ".md"),
25666
- description: (parseFrontmatter(join14(dir, f)).description ?? "").trim(),
25785
+ description: (parseFrontmatter(join12(dir, f)).description ?? "").trim(),
25667
25786
  source,
25668
25787
  kind: "command"
25669
25788
  }));
25670
25789
  const collected = [
25671
- ...local(join14(cwd, ".claude", "commands"), "project"),
25672
- ...local(join14(base, "commands"), "user"),
25673
- ...findPluginMarkdown(join14(base, "plugins"), "commands").map(({ file, plugin }) => ({
25790
+ ...local(join12(cwd, ".claude", "commands"), "project"),
25791
+ ...local(join12(base, "commands"), "user"),
25792
+ ...findPluginMarkdown(join12(base, "plugins"), "commands").map(({ file, plugin }) => ({
25674
25793
  name: plugin ? `${plugin}:${basename3(file, ".md")}` : basename3(file, ".md"),
25675
25794
  description: (parseFrontmatter(file).description ?? "").trim(),
25676
25795
  source: "plugin",
@@ -25692,7 +25811,7 @@ function collectFrom(root, source, maxDepth, namePrefix) {
25692
25811
  findSkillFiles(root, maxDepth, files);
25693
25812
  return files.map((file) => {
25694
25813
  const fm = parseFrontmatter(file);
25695
- const name = fm.name?.trim() || basename3(dirname3(file));
25814
+ const name = fm.name?.trim() || basename3(dirname2(file));
25696
25815
  const plugin = source === "plugin" ? pluginNameFor(file, root) : void 0;
25697
25816
  const prefix = namePrefix ?? plugin;
25698
25817
  return {
@@ -25708,10 +25827,10 @@ function collectFrom(root, source, maxDepth, namePrefix) {
25708
25827
  function collectAll(configDir, cwd) {
25709
25828
  const base = configDir ? expandHome2(configDir) : defaultConfigDir();
25710
25829
  const collected = [
25711
- ...collectFrom(join14(cwd, ".claude", "skills"), "project", 2),
25830
+ ...collectFrom(join12(cwd, ".claude", "skills"), "project", 2),
25712
25831
  ...nestedProjectRoots(cwd).flatMap(({ dir, prefix }) => collectFrom(dir, "project", 2, prefix)),
25713
- ...collectFrom(join14(base, "skills"), "user", 2),
25714
- ...collectFrom(join14(base, "plugins"), "plugin", 8)
25832
+ ...collectFrom(join12(base, "skills"), "user", 2),
25833
+ ...collectFrom(join12(base, "plugins"), "plugin", 8)
25715
25834
  ];
25716
25835
  const byName = /* @__PURE__ */ new Map();
25717
25836
  for (const skill of collected) {
@@ -25730,8 +25849,8 @@ function nestedProjectRoots(cwd) {
25730
25849
  for (const entry of entries2) {
25731
25850
  if (entry.name.startsWith(".") || entry.name === "node_modules") continue;
25732
25851
  if (!entry.isDirectory() && !isSymlinkedDir(cwd, entry)) continue;
25733
- const skillsDir = join14(cwd, entry.name, ".claude", "skills");
25734
- if (existsSync14(skillsDir)) roots.push({ dir: skillsDir, prefix: entry.name });
25852
+ const skillsDir = join12(cwd, entry.name, ".claude", "skills");
25853
+ if (existsSync13(skillsDir)) roots.push({ dir: skillsDir, prefix: entry.name });
25735
25854
  }
25736
25855
  return roots;
25737
25856
  }
@@ -25743,8 +25862,8 @@ function listPluginSkillDetails(configDir, cwd) {
25743
25862
  for (const { file, ...skill } of collectAll(configDir, cwd)) {
25744
25863
  if (skill.source !== "plugin") continue;
25745
25864
  try {
25746
- const { body } = splitFrontmatter(readFileSync12(file, "utf-8"));
25747
- details.push({ ...skill, body, path: file, mtime: statSync5(file).mtime.toISOString() });
25865
+ const { body } = splitFrontmatter(readFileSync10(file, "utf-8"));
25866
+ details.push({ ...skill, body, path: file, mtime: statSync6(file).mtime.toISOString() });
25748
25867
  } catch {
25749
25868
  }
25750
25869
  }
@@ -25753,15 +25872,15 @@ function listPluginSkillDetails(configDir, cwd) {
25753
25872
  function findSkillDetail(configDir, cwd, name, sources) {
25754
25873
  const base = configDir ? expandHome2(configDir) : defaultConfigDir();
25755
25874
  const roots = [
25756
- [join14(cwd, ".claude", "skills"), "project", 2],
25875
+ [join12(cwd, ".claude", "skills"), "project", 2],
25757
25876
  ...nestedProjectRoots(cwd).map(({ dir, prefix }) => [
25758
25877
  dir,
25759
25878
  "project",
25760
25879
  2,
25761
25880
  prefix
25762
25881
  ]),
25763
- [join14(base, "skills"), "user", 2],
25764
- [join14(base, "plugins"), "plugin", 8]
25882
+ [join12(base, "skills"), "user", 2],
25883
+ [join12(base, "plugins"), "plugin", 8]
25765
25884
  ];
25766
25885
  for (const [root, source, maxDepth, namePrefix] of roots) {
25767
25886
  if (!sources.includes(source)) continue;
@@ -25769,7 +25888,7 @@ function findSkillDetail(configDir, cwd, name, sources) {
25769
25888
  findSkillFiles(root, maxDepth, files);
25770
25889
  for (const file of files) {
25771
25890
  const fm = parseFrontmatter(file);
25772
- const rawName = fm.name?.trim() || basename3(dirname3(file));
25891
+ const rawName = fm.name?.trim() || basename3(dirname2(file));
25773
25892
  const plugin = source === "plugin" ? pluginNameFor(file, root) : void 0;
25774
25893
  const prefix = namePrefix ?? plugin;
25775
25894
  const skillName = prefix ? `${prefix}:${rawName}` : rawName;
@@ -25777,8 +25896,8 @@ function findSkillDetail(configDir, cwd, name, sources) {
25777
25896
  let raw;
25778
25897
  let mtime;
25779
25898
  try {
25780
- raw = readFileSync12(file, "utf-8");
25781
- mtime = statSync5(file).mtime.toISOString();
25899
+ raw = readFileSync10(file, "utf-8");
25900
+ mtime = statSync6(file).mtime.toISOString();
25782
25901
  } catch {
25783
25902
  continue;
25784
25903
  }
@@ -25805,24 +25924,24 @@ function expandSkillCommand(configDir, cwd, text) {
25805
25924
  const body = skill.body.includes("$ARGUMENTS") ? skill.body.replaceAll("$ARGUMENTS", args) : skill.body + (args ? `
25806
25925
 
25807
25926
  ARGUMENTS: ${args}` : "");
25808
- return `[the user ran the /${skill.name} skill; its instructions follow. Base directory for this skill: ${dirname3(skill.path)}]
25927
+ return `[the user ran the /${skill.name} skill; its instructions follow. Base directory for this skill: ${dirname2(skill.path)}]
25809
25928
 
25810
25929
  ${body.trim()}`;
25811
25930
  }
25812
25931
 
25813
25932
  // src/claude/agents.ts
25814
25933
  function defaultConfigDir2() {
25815
- return join15(homedir6(), ".claude");
25934
+ return join13(homedir7(), ".claude");
25816
25935
  }
25817
25936
  function expandHome3(p) {
25818
- if (p === "~") return homedir6();
25819
- if (p.startsWith("~/")) return join15(homedir6(), p.slice(2));
25937
+ if (p === "~") return homedir7();
25938
+ if (p.startsWith("~/")) return join13(homedir7(), p.slice(2));
25820
25939
  return p;
25821
25940
  }
25822
25941
  function parseFrontmatter2(file) {
25823
25942
  let content;
25824
25943
  try {
25825
- content = readFileSync13(file, "utf-8");
25944
+ content = readFileSync11(file, "utf-8");
25826
25945
  } catch {
25827
25946
  return {};
25828
25947
  }
@@ -25838,7 +25957,7 @@ function parseFrontmatter2(file) {
25838
25957
  }
25839
25958
  }
25840
25959
  function collectFrom2(root, source) {
25841
- if (!existsSync15(root)) return [];
25960
+ if (!existsSync14(root)) return [];
25842
25961
  let entries2;
25843
25962
  try {
25844
25963
  entries2 = readdirSync5(root).filter((f) => f.endsWith(".md"));
@@ -25846,7 +25965,7 @@ function collectFrom2(root, source) {
25846
25965
  return [];
25847
25966
  }
25848
25967
  return entries2.map((file) => {
25849
- const path = join15(root, file);
25968
+ const path = join13(root, file);
25850
25969
  const fm = parseFrontmatter2(path);
25851
25970
  const name = fm.name?.trim() || basename4(file, ".md");
25852
25971
  return { name, description: (fm.description ?? "").trim(), source, path };
@@ -25855,10 +25974,10 @@ function collectFrom2(root, source) {
25855
25974
  function listAgents(configDir, cwd) {
25856
25975
  const base = configDir ? expandHome3(configDir) : defaultConfigDir2();
25857
25976
  const collected = [
25858
- ...collectFrom2(join15(cwd, ".claude", "agents"), "project"),
25859
- ...collectFrom2(join15(base, "agents"), "user"),
25977
+ ...collectFrom2(join13(cwd, ".claude", "agents"), "project"),
25978
+ ...collectFrom2(join13(base, "agents"), "user"),
25860
25979
  // Plugin agents, namespaced `plugin:agent` the way the CLI lists them.
25861
- ...findPluginMarkdown(join15(base, "plugins"), "agents").map(({ file, plugin }) => {
25980
+ ...findPluginMarkdown(join13(base, "plugins"), "agents").map(({ file, plugin }) => {
25862
25981
  const fm = parseFrontmatter2(file);
25863
25982
  const name = fm.name?.trim() || basename4(file, ".md");
25864
25983
  return {
@@ -25879,7 +25998,7 @@ function readAgentPersona(configDir, cwd, name) {
25879
25998
  const agent = listAgents(configDir, cwd).find((a) => a.name === name);
25880
25999
  if (!agent) return void 0;
25881
26000
  try {
25882
- const content = readFileSync13(agent.path, "utf-8");
26001
+ const content = readFileSync11(agent.path, "utf-8");
25883
26002
  return content.replace(/^---\r?\n[\s\S]*?\r?\n---\r?\n?/, "").trim();
25884
26003
  } catch {
25885
26004
  return void 0;
@@ -25888,13 +26007,13 @@ function readAgentPersona(configDir, cwd, name) {
25888
26007
 
25889
26008
  // src/dashboard/memory-extraction-runner.ts
25890
26009
  import { spawn as spawn4 } from "child_process";
25891
- import { existsSync as existsSync16, mkdtempSync as mkdtempSync5, readFileSync as readFileSync14, rmSync as rmSync10 } from "fs";
26010
+ import { existsSync as existsSync15, mkdtempSync as mkdtempSync5, readFileSync as readFileSync12, rmSync as rmSync8 } from "fs";
25892
26011
  import { tmpdir as tmpdir4 } from "os";
25893
- import { join as join17 } from "path";
26012
+ import { join as join15 } from "path";
25894
26013
 
25895
26014
  // ../api/src/dashboard/profile-config.ts
25896
- import { homedir as homedir7 } from "os";
25897
- import { join as join16, parse, resolve as resolve6 } from "path";
26015
+ import { homedir as homedir8 } from "os";
26016
+ import { join as join14, parse, resolve as resolve6 } from "path";
25898
26017
 
25899
26018
  // ../api/src/dashboard/profile-config-cache.ts
25900
26019
  var cache3 = /* @__PURE__ */ new Map();
@@ -25913,7 +26032,7 @@ function profileEnv(key) {
25913
26032
  function profileClaudeConfigDir() {
25914
26033
  const config = cachedProfileConfig();
25915
26034
  if (!config) return process.env["CLAUDE_CONFIG_DIR"] || void 0;
25916
- return config.env["CLAUDE_CONFIG_DIR"]?.trim() || join16(homedir7(), ".claude");
26035
+ return config.env["CLAUDE_CONFIG_DIR"]?.trim() || join14(homedir8(), ".claude");
25917
26036
  }
25918
26037
  function profileOauthToken() {
25919
26038
  const env = cachedProfileConfig()?.env ?? {};
@@ -25923,7 +26042,7 @@ function profileOauthToken() {
25923
26042
  }
25924
26043
  function isUnsafeCwd(cwd) {
25925
26044
  const p = resolve6(cwd);
25926
- return p === parse(p).root || p === resolve6(homedir7());
26045
+ return p === parse(p).root || p === resolve6(homedir8());
25927
26046
  }
25928
26047
  function defaultClaudeCwd() {
25929
26048
  return profileEnv("CLAUDE_CWD") ?? process.cwd();
@@ -25974,7 +26093,7 @@ var SUGGEST_TOOLS = "Read,Glob,Grep";
25974
26093
  function buildInvocation(runner, req, dir, auth, baseEnv = process.env, tools = "") {
25975
26094
  const env = { ...baseEnv, CLAUDE_CODE_DISABLE_AUTO_MEMORY: "1" };
25976
26095
  if (runner === "codex") {
25977
- const outputFile = join17(dir, "last-message.txt");
26096
+ const outputFile = join15(dir, "last-message.txt");
25978
26097
  return {
25979
26098
  command: "codex",
25980
26099
  args: [
@@ -26030,7 +26149,7 @@ ${req.user}`,
26030
26149
  }
26031
26150
  function run(inv, cwd) {
26032
26151
  return new Promise((resolve8) => {
26033
- if (!existsSync16(cwd)) {
26152
+ if (!existsSync15(cwd)) {
26034
26153
  resolve8({ ok: false, error: `the channel folder ${cwd} does not exist on this Host` });
26035
26154
  return;
26036
26155
  }
@@ -26063,7 +26182,7 @@ function run(inv, cwd) {
26063
26182
  let raw = stdout;
26064
26183
  if (inv.outputFile) {
26065
26184
  try {
26066
- raw = readFileSync14(inv.outputFile, "utf-8");
26185
+ raw = readFileSync12(inv.outputFile, "utf-8");
26067
26186
  } catch {
26068
26187
  raw = "";
26069
26188
  }
@@ -26076,7 +26195,7 @@ function run(inv, cwd) {
26076
26195
  async function complete(req, tools = "", cwd) {
26077
26196
  const runner = runnerForModel(loadDashboardSettings().agent);
26078
26197
  const config = resolveChannelConfig(req.channelId);
26079
- const dir = mkdtempSync5(join17(tmpdir4(), "flyspace-memory-"));
26198
+ const dir = mkdtempSync5(join15(tmpdir4(), "flyspace-memory-"));
26080
26199
  try {
26081
26200
  const inv = buildInvocation(
26082
26201
  runner,
@@ -26091,7 +26210,7 @@ async function complete(req, tools = "", cwd) {
26091
26210
  );
26092
26211
  return await run(inv, cwd ?? dir);
26093
26212
  } finally {
26094
- rmSync10(dir, { recursive: true, force: true });
26213
+ rmSync8(dir, { recursive: true, force: true });
26095
26214
  }
26096
26215
  }
26097
26216
  function completeMemoryExtraction(req) {
@@ -26104,7 +26223,7 @@ function suggestChannelField(req) {
26104
26223
  }
26105
26224
 
26106
26225
  // src/store/usage-store.ts
26107
- import { randomUUID as randomUUID3 } from "crypto";
26226
+ import { randomUUID as randomUUID2 } from "crypto";
26108
26227
  import Database2 from "better-sqlite3";
26109
26228
 
26110
26229
  // ../api/src/store/rate-cards.ts
@@ -26445,7 +26564,7 @@ var UsageStore = class {
26445
26564
  if (ids.length === 0) return;
26446
26565
  const update = this.db.prepare("UPDATE agent_usage SET row_uid = ? WHERE id = ?");
26447
26566
  this.db.transaction(() => {
26448
- for (const { id } of ids) update.run(randomUUID3(), id);
26567
+ for (const { id } of ids) update.run(randomUUID2(), id);
26449
26568
  })();
26450
26569
  }
26451
26570
  /**
@@ -26483,7 +26602,7 @@ var UsageStore = class {
26483
26602
  cost_usd, duration_ms, num_turns, is_error
26484
26603
  ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`
26485
26604
  ).run(
26486
- randomUUID3(),
26605
+ randomUUID2(),
26487
26606
  ranAt.toISOString(),
26488
26607
  entry.source,
26489
26608
  entry.channelId ?? null,
@@ -26791,9 +26910,9 @@ var UsageStore = class {
26791
26910
 
26792
26911
  // src/dashboard/rollover-summary.ts
26793
26912
  import { spawn as spawn5 } from "child_process";
26794
- import { existsSync as existsSync17, mkdtempSync as mkdtempSync6, readFileSync as readFileSync15, rmSync as rmSync11 } from "fs";
26913
+ import { existsSync as existsSync16, mkdtempSync as mkdtempSync6, readFileSync as readFileSync13, rmSync as rmSync9 } from "fs";
26795
26914
  import { tmpdir as tmpdir5 } from "os";
26796
- import { join as join18 } from "path";
26915
+ import { join as join16 } from "path";
26797
26916
  var HAIKU_MODEL = "haiku";
26798
26917
  var CJK_PATTERN = /[ -〿぀-ヿ㐀-䶿一-鿿豈-﫿＀-￯]/;
26799
26918
  function estimateTokens(text) {
@@ -26856,8 +26975,8 @@ function runSummaryPrint(input, options) {
26856
26975
  return runPrint("claude", args, env).then((out) => out.trim());
26857
26976
  }
26858
26977
  async function runCodexSummary(input) {
26859
- const dir = mkdtempSync6(join18(tmpdir5(), "rollover-"));
26860
- const lastMessageFile = join18(dir, "last-message.txt");
26978
+ const dir = mkdtempSync6(join16(tmpdir5(), "rollover-"));
26979
+ const lastMessageFile = join16(dir, "last-message.txt");
26861
26980
  try {
26862
26981
  await runPrint(
26863
26982
  "codex",
@@ -26880,9 +26999,9 @@ ${input}`
26880
26999
  ],
26881
27000
  { ...process.env }
26882
27001
  );
26883
- return existsSync17(lastMessageFile) ? readFileSync15(lastMessageFile, "utf8").trim() : "";
27002
+ return existsSync16(lastMessageFile) ? readFileSync13(lastMessageFile, "utf8").trim() : "";
26884
27003
  } finally {
26885
- rmSync11(dir, { recursive: true, force: true });
27004
+ rmSync9(dir, { recursive: true, force: true });
26886
27005
  }
26887
27006
  }
26888
27007
  function runPrint(command, args, env) {
@@ -27122,7 +27241,7 @@ async function scanBackgroundTasks() {
27122
27241
 
27123
27242
  // src/dashboard/attachment-downloader.ts
27124
27243
  import { writeFile as writeFile2 } from "fs/promises";
27125
- import { join as join19 } from "path";
27244
+ import { join as join17 } from "path";
27126
27245
  import { GetObjectCommand } from "@aws-sdk/client-s3";
27127
27246
  var debug4 = process.env["DEBUG"] === "true";
27128
27247
  var ATTACHMENT_LINK = /\]\((?:https:\/\/[a-z0-9-]+\.flyspace\.ai)?\/api\/attachments\/([^)?\s]+)(?:\?[^)\s]*)?\)/g;
@@ -27189,7 +27308,7 @@ async function downloadOne2(key) {
27189
27308
  if (bytes.length > sizeLimit) {
27190
27309
  return { kind: "skip", skipped: { name, mimetype, reason: "too_large" } };
27191
27310
  }
27192
- const localPath = join19(paths.UPLOADS_DIR, lastSegment);
27311
+ const localPath = join17(paths.UPLOADS_DIR, lastSegment);
27193
27312
  await writeFile2(localPath, bytes);
27194
27313
  if (debug4)
27195
27314
  console.log(`[attachment-downloader] saved ${key} -> ${localPath} (${bytes.length} bytes)`);
@@ -27214,10 +27333,10 @@ async function downloadChatAttachments(body) {
27214
27333
  }
27215
27334
 
27216
27335
  // src/dashboard/plugin-ui-store.ts
27217
- import { createHash as createHash5 } from "crypto";
27336
+ import { createHash as createHash6 } from "crypto";
27218
27337
  var INLINE_MAX = 2048;
27219
27338
  var uploaded = /* @__PURE__ */ new Map();
27220
- var sha256 = (s) => createHash5("sha256").update(s).digest("hex");
27339
+ var sha256 = (s) => createHash6("sha256").update(s).digest("hex");
27221
27340
  async function offloadSvg(workspace, source) {
27222
27341
  const cacheKey2 = `${workspace}:${sha256(source)}`;
27223
27342
  const cached = uploaded.get(cacheKey2);
@@ -27249,27 +27368,27 @@ async function offloadPluginUi(workspace, state) {
27249
27368
  var pluginUiHash = (state) => sha256(JSON.stringify(state));
27250
27369
 
27251
27370
  // src/dashboard/doc-mention-guard.ts
27252
- import { existsSync as existsSync22, statSync as statSync8 } from "fs";
27371
+ import { existsSync as existsSync21, statSync as statSync9 } from "fs";
27253
27372
 
27254
27373
  // src/dashboard/docs-routes.ts
27255
27374
  import {
27256
27375
  closeSync,
27257
27376
  createReadStream,
27258
- existsSync as existsSync21,
27377
+ existsSync as existsSync20,
27259
27378
  lstatSync as lstatSync2,
27260
- mkdirSync as mkdirSync10,
27379
+ mkdirSync as mkdirSync9,
27261
27380
  openSync,
27262
27381
  readSync,
27263
27382
  readdirSync as readdirSync6,
27264
- readFileSync as readFileSync19,
27265
- realpathSync,
27383
+ readFileSync as readFileSync17,
27384
+ realpathSync as realpathSync2,
27266
27385
  renameSync as renameSync3,
27267
- rmSync as rmSync12,
27268
- statSync as statSync7,
27269
- writeFileSync as writeFileSync9
27386
+ rmSync as rmSync10,
27387
+ statSync as statSync8,
27388
+ writeFileSync as writeFileSync7
27270
27389
  } from "fs";
27271
27390
  import { Readable } from "stream";
27272
- import { basename as basename6, dirname as dirname4, extname as extname2, join as join23, relative, resolve as resolve7, sep as sep3 } from "path";
27391
+ import { basename as basename6, dirname as dirname3, extname as extname2, join as join21, relative as relative2, resolve as resolve7, sep as sep4 } from "path";
27273
27392
  import { Hono as Hono4 } from "hono";
27274
27393
  import { streamSSE } from "hono/streaming";
27275
27394
 
@@ -27381,8 +27500,8 @@ var requireDocsAccess = async (c, next) => {
27381
27500
  };
27382
27501
 
27383
27502
  // src/dashboard/docs-watcher.ts
27384
- import { existsSync as existsSync18, watch } from "fs";
27385
- import { basename as basename5, join as join20 } from "path";
27503
+ import { existsSync as existsSync17, watch } from "fs";
27504
+ import { basename as basename5, join as join18 } from "path";
27386
27505
  var DEBOUNCE_MS = 200;
27387
27506
  var MAX_PENDING = 200;
27388
27507
  var IGNORED_SEGMENTS = /* @__PURE__ */ new Set([
@@ -27423,7 +27542,7 @@ function watchDocs(cwd, listener) {
27423
27542
  const current = entries.get(cwd);
27424
27543
  if (!current || filename === null) return;
27425
27544
  const rel = filename.split("\\").join("/");
27426
- if (rel === root && !existsSync18(join20(cwd, rel))) return;
27545
+ if (rel === root && !existsSync17(join18(cwd, rel))) return;
27427
27546
  if (isIgnoredDocPath(rel)) return;
27428
27547
  if (current.pending.size < MAX_PENDING) current.pending.add(rel);
27429
27548
  if (current.timer === null) current.timer = setTimeout(() => flush(cwd), DEBOUNCE_MS);
@@ -27477,7 +27596,7 @@ async function putDocTranslation(input) {
27477
27596
  }
27478
27597
 
27479
27598
  // ../api/src/dashboard/share-translate.ts
27480
- import { createHash as createHash6 } from "crypto";
27599
+ import { createHash as createHash7 } from "crypto";
27481
27600
 
27482
27601
  // ../api/src/store/doc-share-store.ts
27483
27602
  function rowToKind(value) {
@@ -27787,7 +27906,7 @@ function languageName(lang) {
27787
27906
  return BY_CODE.get(lang)?.name ?? null;
27788
27907
  }
27789
27908
  function translationHash(title, content) {
27790
- return createHash6("sha256").update(`${RECIPE_VERSION}
27909
+ return createHash7("sha256").update(`${RECIPE_VERSION}
27791
27910
  ${title}
27792
27911
  ${content}`).digest("hex");
27793
27912
  }
@@ -28022,7 +28141,7 @@ async function clearStaleDocAudios(channelId, sourcePath, lang, exceptHash) {
28022
28141
  }
28023
28142
 
28024
28143
  // ../api/src/dashboard/share-audio.ts
28025
- import { createHash as createHash7 } from "crypto";
28144
+ import { createHash as createHash8 } from "crypto";
28026
28145
  import { DeleteObjectCommand, PutObjectCommand as PutObjectCommand2 } from "@aws-sdk/client-s3";
28027
28146
 
28028
28147
  // ../api/src/dashboard/tts-routes.ts
@@ -28221,7 +28340,7 @@ Pacing \u2014 the engine has NO pause control, so rhythm has to be built into th
28221
28340
  Output plain text ONLY. No tags of any kind, no angle brackets, no Markdown, no quotation wrapping. Any tag you emit will be deleted before synthesis, so it buys nothing and costs meaning.`;
28222
28341
  }
28223
28342
  function articleAudioHash(title, content) {
28224
- return createHash7("sha256").update(`v${RECIPE_VERSION2}
28343
+ return createHash8("sha256").update(`v${RECIPE_VERSION2}
28225
28344
  ${title}
28226
28345
 
28227
28346
  ${content}`).digest("hex").slice(0, 32);
@@ -28448,7 +28567,7 @@ function queueShareAudio(share) {
28448
28567
  var PENDING_STALE_MS = 30 * 60 * 1e3;
28449
28568
  var FAILED_RETRY_MS = 10 * 60 * 1e3;
28450
28569
  function langAudioHash(title, content, lang) {
28451
- return createHash7("sha256").update(`v${RECIPE_VERSION2}
28570
+ return createHash8("sha256").update(`v${RECIPE_VERSION2}
28452
28571
  ${lang}
28453
28572
  ${translationHash(title, content)}`).digest("hex").slice(0, 32);
28454
28573
  }
@@ -28735,8 +28854,8 @@ function createFeatureFlagsRouter() {
28735
28854
  }
28736
28855
 
28737
28856
  // ../api/src/dashboard/public-share-routes.ts
28738
- import { existsSync as existsSync20, readFileSync as readFileSync17, statSync as statSync6 } from "fs";
28739
- import { join as join22 } from "path";
28857
+ import { existsSync as existsSync19, readFileSync as readFileSync15, statSync as statSync7 } from "fs";
28858
+ import { join as join20 } from "path";
28740
28859
  import { Hono as Hono3 } from "hono";
28741
28860
  import { GetObjectCommand as GetObjectCommand3 } from "@aws-sdk/client-s3";
28742
28861
  import { getSignedUrl as getSignedUrl2 } from "@aws-sdk/s3-request-presigner";
@@ -28942,14 +29061,14 @@ function injectShareHead(html, head) {
28942
29061
  }
28943
29062
 
28944
29063
  // ../api/src/dashboard/app-icon.ts
28945
- import { createHash as createHash8 } from "crypto";
28946
- import { existsSync as existsSync19, readFileSync as readFileSync16 } from "fs";
28947
- import { join as join21 } from "path";
29064
+ import { createHash as createHash9 } from "crypto";
29065
+ import { existsSync as existsSync18, readFileSync as readFileSync14 } from "fs";
29066
+ import { join as join19 } from "path";
28948
29067
  import sharp3 from "sharp";
28949
29068
  var PLATE = "#0A0A0F";
28950
- var BRAND_DIR = existsSync19(join21(paths.WEB_ROOT, "public")) ? join21(paths.WEB_ROOT, "public") : join21(paths.PACKAGE_ROOT, "dist", "brand");
28951
- var MARK_FILE = join21(BRAND_DIR, "icons", "icon-512.png");
28952
- var MARK_SVG_FILE = join21(BRAND_DIR, "favicon.svg");
29069
+ var BRAND_DIR = existsSync18(join19(paths.WEB_ROOT, "public")) ? join19(paths.WEB_ROOT, "public") : join19(paths.PACKAGE_ROOT, "dist", "brand");
29070
+ var MARK_FILE = join19(BRAND_DIR, "icons", "icon-512.png");
29071
+ var MARK_SVG_FILE = join19(BRAND_DIR, "favicon.svg");
28953
29072
  var LAYOUT = {
28954
29073
  standard: { logo: 0.7, logoCx: 0.5, logoCy: 0.48, badge: 0.27, badgeCx: 0.22, badgeCy: 0.76 },
28955
29074
  maskable: { logo: 0.56, logoCx: 0.5, logoCy: 0.48, badge: 0.23, badgeCx: 0.33, badgeCy: 0.66 }
@@ -28972,7 +29091,7 @@ function roundedPlate(size, fill = PLATE) {
28972
29091
  }
28973
29092
  async function renderBadge(box) {
28974
29093
  const transparent = { r: 0, g: 0, b: 0, alpha: 0 };
28975
- const raster = await sharp3(readFileSync16(MARK_SVG_FILE)).resize(512, 512, { fit: "contain", background: transparent }).png().toBuffer();
29094
+ const raster = await sharp3(readFileSync14(MARK_SVG_FILE)).resize(512, 512, { fit: "contain", background: transparent }).png().toBuffer();
28976
29095
  return sharp3(raster).trim().resize(box, box, { fit: "contain", background: transparent }).png().toBuffer();
28977
29096
  }
28978
29097
  async function sampleBackground(logo) {
@@ -29021,13 +29140,13 @@ async function renderAppIcon({
29021
29140
  size,
29022
29141
  maskable ? "maskable" : "std",
29023
29142
  plain ? "plain" : "badged",
29024
- logo ? createHash8("sha1").update(logo).digest("hex").slice(0, 12) : transparent ? "stock-transparent" : "stock"
29143
+ logo ? createHash9("sha1").update(logo).digest("hex").slice(0, 12) : transparent ? "stock-transparent" : "stock"
29025
29144
  ].join(":");
29026
29145
  const hit = cache4.get(key);
29027
29146
  if (hit) return hit;
29028
29147
  const out = logo && await composeIcon(logo, size, maskable, plain).catch(() => null) || // No workspace logo to lead with — the stock mark is still the best icon,
29029
29148
  // either on its usual dark plate or, for a favicon, trimmed and bare.
29030
- (transparent ? await renderBadge(size) : await sharp3(readFileSync16(MARK_FILE)).resize(size, size, { fit: "cover" }).png().toBuffer());
29149
+ (transparent ? await renderBadge(size) : await sharp3(readFileSync14(MARK_FILE)).resize(size, size, { fit: "cover" }).png().toBuffer());
29031
29150
  cache4.set(key, out);
29032
29151
  return out;
29033
29152
  }
@@ -29052,7 +29171,7 @@ async function composeIcon(logo, size, maskable, plain) {
29052
29171
  }
29053
29172
 
29054
29173
  // ../api/src/dashboard/share-og.ts
29055
- import { createHash as createHash9 } from "crypto";
29174
+ import { createHash as createHash10 } from "crypto";
29056
29175
  import sharp4 from "sharp";
29057
29176
  var WIDTH = 1200;
29058
29177
  var HEIGHT = 630;
@@ -29230,7 +29349,7 @@ function cacheKey(input) {
29230
29349
  input.logo ?? "",
29231
29350
  input.theme ?? ""
29232
29351
  ];
29233
- return createHash9("sha1").update(parts.join("\0")).digest("hex");
29352
+ return createHash10("sha1").update(parts.join("\0")).digest("hex");
29234
29353
  }
29235
29354
  async function renderShareOgImage(input) {
29236
29355
  const key = cacheKey(input);
@@ -29245,7 +29364,7 @@ async function renderShareOgImage(input) {
29245
29364
  }
29246
29365
 
29247
29366
  // ../api/src/dashboard/share-ask.ts
29248
- import { createHash as createHash10 } from "crypto";
29367
+ import { createHash as createHash11 } from "crypto";
29249
29368
  var MAX_ARTICLE_CHARS3 = 24e3;
29250
29369
  var MAX_QUESTION_CHARS = 500;
29251
29370
  var SUGGESTION_COUNT = 4;
@@ -29310,7 +29429,7 @@ function parseSuggestions(raw) {
29310
29429
  var CACHE_LIMIT = 200;
29311
29430
  var suggestionCache = /* @__PURE__ */ new Map();
29312
29431
  function articleHash(title, content, lang) {
29313
- return createHash10("sha256").update(`${lang ?? ""}
29432
+ return createHash11("sha256").update(`${lang ?? ""}
29314
29433
  ${title}
29315
29434
 
29316
29435
  ${content}`).digest("hex").slice(0, 32);
@@ -29564,9 +29683,9 @@ function createPublicShareApiRouter() {
29564
29683
  var BUILD_PREFIX = "/share/_assets";
29565
29684
  var shellCache = null;
29566
29685
  function readShell(path) {
29567
- const { mtimeMs } = statSync6(path);
29686
+ const { mtimeMs } = statSync7(path);
29568
29687
  if (shellCache?.mtimeMs === mtimeMs) return shellCache.html;
29569
- const html = readFileSync17(path, "utf8").replaceAll('"/assets/', `"${BUILD_PREFIX}/`);
29688
+ const html = readFileSync15(path, "utf8").replaceAll('"/assets/', `"${BUILD_PREFIX}/`);
29570
29689
  shellCache = { mtimeMs, html };
29571
29690
  return html;
29572
29691
  }
@@ -29586,17 +29705,17 @@ function serveBuildFile(c, webDist, dir, name) {
29586
29705
  if (!type || !/^[A-Za-z0-9._-]+$/.test(name) || name.includes("..")) {
29587
29706
  return c.text("not found", 404);
29588
29707
  }
29589
- const path = join22(webDist, dir, name);
29590
- if (!existsSync20(path)) return c.text("not found", 404);
29708
+ const path = join20(webDist, dir, name);
29709
+ if (!existsSync19(path)) return c.text("not found", 404);
29591
29710
  c.header("Content-Type", type);
29592
29711
  c.header("Cache-Control", "public, max-age=31536000, immutable");
29593
29712
  if (ext === ".css") {
29594
- return c.body(readFileSync17(path, "utf8").replaceAll("url(/fonts/", `url(${BUILD_PREFIX}/fonts/`));
29713
+ return c.body(readFileSync15(path, "utf8").replaceAll("url(/fonts/", `url(${BUILD_PREFIX}/fonts/`));
29595
29714
  }
29596
29715
  if (ext === ".js") {
29597
- return c.body(readFileSync17(path, "utf8").replaceAll('"/assets/', `"${BUILD_PREFIX}/`));
29716
+ return c.body(readFileSync15(path, "utf8").replaceAll('"/assets/', `"${BUILD_PREFIX}/`));
29598
29717
  }
29599
- return c.body(new Uint8Array(readFileSync17(path)));
29718
+ return c.body(new Uint8Array(readFileSync15(path)));
29600
29719
  }
29601
29720
  var HTML_SHARE_CSP = "sandbox allow-scripts allow-forms allow-modals allow-popups allow-popups-to-escape-sandbox";
29602
29721
  function servePublishedHtml(c, share) {
@@ -29732,8 +29851,8 @@ ${analytics}` : head);
29732
29851
  const requested = c.req.param("lang");
29733
29852
  const lang = canonicalLanguage(requested);
29734
29853
  if (!isTranslatableLanguage(lang)) return next();
29735
- const shell = join22(webDist, "index.html");
29736
- if (!existsSync20(shell)) return next();
29854
+ const shell = join20(webDist, "index.html");
29855
+ if (!existsSync19(shell)) return next();
29737
29856
  const share = await getDocShare(c.req.param("id"));
29738
29857
  if (!share) return next();
29739
29858
  if (requested !== lang) return c.redirect(`/share/${share.id}/${lang}`, 302);
@@ -29768,8 +29887,8 @@ ${analytics}` : head);
29768
29887
  const share = await getDocShare(c.req.param("id"));
29769
29888
  if (!share) return next();
29770
29889
  if (share.kind === "html") return servePublishedHtml(c, share);
29771
- const shell = join22(webDist, "index.html");
29772
- if (!existsSync20(shell)) return next();
29890
+ const shell = join20(webDist, "index.html");
29891
+ if (!existsSync19(shell)) return next();
29773
29892
  return readerPage(
29774
29893
  c,
29775
29894
  share,
@@ -29794,7 +29913,7 @@ ${analytics}` : head);
29794
29913
  }
29795
29914
 
29796
29915
  // src/dashboard/artifact-export.ts
29797
- import { readFileSync as readFileSync18 } from "fs";
29916
+ import { readFileSync as readFileSync16 } from "fs";
29798
29917
  async function exportDocAsArtifact(channelId, docPath) {
29799
29918
  const owningProfile = findOwningProfile(channelId);
29800
29919
  const channelConfig = await runWithProfile(
@@ -29803,7 +29922,7 @@ async function exportDocAsArtifact(channelId, docPath) {
29803
29922
  );
29804
29923
  const abs = resolveDocPath(channelConfig.cwd, docPath);
29805
29924
  if (!abs) throw new Error(`doc not found: ${docPath}`);
29806
- const content = readFileSync18(abs, "utf8");
29925
+ const content = readFileSync16(abs, "utf8");
29807
29926
  const title = extractTitle(abs, "md");
29808
29927
  const today = (/* @__PURE__ */ new Date()).toISOString().slice(0, 10);
29809
29928
  const prompt = `Publish the document at \`${docPath}\` (already read below) as a Claude Artifact, then record the result as a stub file under this channel's \`docs/artifacts/\` folder (create the folder if it doesn't exist).
@@ -29965,7 +30084,7 @@ function entryKind(entry, abs) {
29965
30084
  if (entry.isFile()) return "file";
29966
30085
  if (!entry.isSymbolicLink()) return null;
29967
30086
  try {
29968
- const target = statSync7(abs);
30087
+ const target = statSync8(abs);
29969
30088
  return target.isDirectory() ? "dir" : target.isFile() ? "file" : null;
29970
30089
  } catch {
29971
30090
  return null;
@@ -29978,11 +30097,11 @@ function fileNode(root, abs, name) {
29978
30097
  const lang = CODE_EXTENSIONS[ext];
29979
30098
  let stat;
29980
30099
  try {
29981
- stat = statSync7(abs);
30100
+ stat = statSync8(abs);
29982
30101
  } catch {
29983
30102
  return null;
29984
30103
  }
29985
- const path = relative(root, abs).split(sep3).join("/");
30104
+ const path = relative2(root, abs).split(sep4).join("/");
29986
30105
  const mtime = stat.mtime.toISOString();
29987
30106
  if (kind) {
29988
30107
  return {
@@ -30036,7 +30155,7 @@ function extractTitle(absPath, kind) {
30036
30155
  function resolveDirPath(root, rel) {
30037
30156
  if (rel.includes("\0")) return null;
30038
30157
  const abs = resolve7(root, rel);
30039
- if (abs !== root && !abs.startsWith(root + sep3)) return null;
30158
+ if (abs !== root && !abs.startsWith(root + sep4)) return null;
30040
30159
  return abs;
30041
30160
  }
30042
30161
  function isListableFile(name) {
@@ -30063,7 +30182,7 @@ function probeDir(absDir, showHidden) {
30063
30182
  return false;
30064
30183
  }
30065
30184
  if (!showHidden && entry.name.startsWith(".")) continue;
30066
- const abs = join23(dir, entry.name);
30185
+ const abs = join21(dir, entry.name);
30067
30186
  const kind = entryKind(entry, abs);
30068
30187
  if (kind === "dir") {
30069
30188
  if (SKIP_DIRS.has(entry.name)) hasOther = true;
@@ -30083,14 +30202,14 @@ function probeDir(absDir, showHidden) {
30083
30202
  }
30084
30203
  function readGitBranch(dir) {
30085
30204
  try {
30086
- let gitDir = join23(dir, ".git");
30087
- if (statSync7(gitDir).isFile()) {
30088
- const pointer = readFileSync19(gitDir, "utf8").trim();
30205
+ let gitDir = join21(dir, ".git");
30206
+ if (statSync8(gitDir).isFile()) {
30207
+ const pointer = readFileSync17(gitDir, "utf8").trim();
30089
30208
  const match = pointer.match(/^gitdir:\s*(.+)$/);
30090
30209
  if (!match) return void 0;
30091
30210
  gitDir = resolve7(dir, match[1]);
30092
30211
  }
30093
- const head = readFileSync19(join23(gitDir, "HEAD"), "utf8").trim();
30212
+ const head = readFileSync17(join21(gitDir, "HEAD"), "utf8").trim();
30094
30213
  const branchMatch = head.match(/^ref:\s*refs\/heads\/(.+)$/);
30095
30214
  if (branchMatch) return branchMatch[1];
30096
30215
  return /^[0-9a-f]{7,40}$/i.test(head) ? head.slice(0, 7) : void 0;
@@ -30112,14 +30231,14 @@ function listDocLevel(root, relDir = "", sort = "newest", showHidden = false) {
30112
30231
  for (const entry of entries2) {
30113
30232
  if (dirs.length + docs.length >= MAX_ENTRIES) break;
30114
30233
  if (!showHidden && entry.name.startsWith(".")) continue;
30115
- const abs = join23(absDir, entry.name);
30116
- const path = relative(root, abs).split(sep3).join("/");
30234
+ const abs = join21(absDir, entry.name);
30235
+ const path = relative2(root, abs).split(sep4).join("/");
30117
30236
  const kind = entryKind(entry, abs);
30118
30237
  if (kind === "dir") {
30119
30238
  if (SKIP_DIRS.has(entry.name)) continue;
30120
30239
  const probe = probeDir(abs, showHidden);
30121
30240
  if (!probe.hasDocs && probe.hasOther) continue;
30122
- const isRepo = existsSync21(join23(abs, ".git"));
30241
+ const isRepo = existsSync20(join21(abs, ".git"));
30123
30242
  dirs.push({
30124
30243
  path,
30125
30244
  name: entry.name,
@@ -30155,7 +30274,7 @@ function flatDocs(root, {
30155
30274
  for (const entry of entries2) {
30156
30275
  if (hits.length >= MAX_FLAT_DOCS) return;
30157
30276
  if (!showHidden && entry.name.startsWith(".")) continue;
30158
- const abs = join23(dir, entry.name);
30277
+ const abs = join21(dir, entry.name);
30159
30278
  const kind = entryKind(entry, abs);
30160
30279
  if (kind === "dir") {
30161
30280
  if (!SKIP_DIRS.has(entry.name)) walk(abs, depth + 1);
@@ -30176,7 +30295,7 @@ function flatDocs(root, {
30176
30295
  function resolveDocPath(root, rel) {
30177
30296
  if (!rel || rel.includes("\0")) return null;
30178
30297
  const abs = resolve7(root, rel);
30179
- if (abs !== root && !abs.startsWith(root + sep3)) return null;
30298
+ if (abs !== root && !abs.startsWith(root + sep4)) return null;
30180
30299
  const ext = extname2(abs).toLowerCase();
30181
30300
  if (!(ext in DOC_EXTENSIONS) && !(ext in CODE_EXTENSIONS)) return null;
30182
30301
  return abs;
@@ -30186,7 +30305,7 @@ function writeDocContent(root, rel, content, baseMtime) {
30186
30305
  if (!abs) return { status: "not-found" };
30187
30306
  let stat;
30188
30307
  try {
30189
- stat = statSync7(abs);
30308
+ stat = statSync8(abs);
30190
30309
  } catch {
30191
30310
  return { status: "not-found" };
30192
30311
  }
@@ -30197,13 +30316,13 @@ function writeDocContent(root, rel, content, baseMtime) {
30197
30316
  if (Buffer.byteLength(content, "utf8") > MAX_CONTENT_BYTES) {
30198
30317
  return { status: "too-large" };
30199
30318
  }
30200
- writeFileSync9(abs, content, "utf8");
30201
- return { status: "ok", mtime: statSync7(abs).mtime.toISOString() };
30319
+ writeFileSync7(abs, content, "utf8");
30320
+ return { status: "ok", mtime: statSync8(abs).mtime.toISOString() };
30202
30321
  }
30203
30322
  function resolveRawPath(root, rel) {
30204
30323
  if (!rel || rel.includes("\0")) return null;
30205
30324
  const abs = resolve7(root, rel);
30206
- if (abs !== root && !abs.startsWith(root + sep3)) return null;
30325
+ if (abs !== root && !abs.startsWith(root + sep4)) return null;
30207
30326
  const contentType = MEDIA_EXTENSIONS[extname2(abs).toLowerCase()];
30208
30327
  if (!contentType) return null;
30209
30328
  return { abs, contentType };
@@ -30211,14 +30330,14 @@ function resolveRawPath(root, rel) {
30211
30330
  function resolveHtmlPath(root, rel) {
30212
30331
  if (!rel || rel.includes("\0")) return null;
30213
30332
  const abs = resolve7(root, rel);
30214
- if (abs !== root && !abs.startsWith(root + sep3)) return null;
30333
+ if (abs !== root && !abs.startsWith(root + sep4)) return null;
30215
30334
  if (DOC_EXTENSIONS[extname2(abs).toLowerCase()] !== "html") return null;
30216
30335
  return abs;
30217
30336
  }
30218
30337
  function resolveDownloadPath(root, rel) {
30219
30338
  if (!rel || rel.includes("\0")) return null;
30220
30339
  const abs = resolve7(root, rel);
30221
- if (abs !== root && !abs.startsWith(root + sep3)) return null;
30340
+ if (abs !== root && !abs.startsWith(root + sep4)) return null;
30222
30341
  if (!isListableFile(basename6(abs))) return null;
30223
30342
  const contentType = MEDIA_EXTENSIONS[extname2(abs).toLowerCase()] ?? "application/octet-stream";
30224
30343
  return { abs, contentType };
@@ -30235,7 +30354,7 @@ function uniqueName(absDir, name) {
30235
30354
  let candidate = name;
30236
30355
  for (let n = 1; n < 1e3; n++) {
30237
30356
  try {
30238
- statSync7(join23(absDir, candidate));
30357
+ statSync8(join21(absDir, candidate));
30239
30358
  } catch {
30240
30359
  return candidate;
30241
30360
  }
@@ -30247,7 +30366,7 @@ function saveUploadedFile(root, relDir, name, data) {
30247
30366
  const absDir = resolveDirPath(root, relDir);
30248
30367
  if (absDir === null) return { status: "no-dir" };
30249
30368
  try {
30250
- if (!statSync7(absDir).isDirectory()) return { status: "no-dir" };
30369
+ if (!statSync8(absDir).isDirectory()) return { status: "no-dir" };
30251
30370
  } catch {
30252
30371
  return { status: "no-dir" };
30253
30372
  }
@@ -30257,34 +30376,34 @@ function saveUploadedFile(root, relDir, name, data) {
30257
30376
  if (!(ext in DOC_EXTENSIONS) && !ASSET_LIST_EXTENSIONS.has(ext)) return { status: "bad-type" };
30258
30377
  if (data.byteLength > MAX_UPLOAD_BYTES) return { status: "too-large" };
30259
30378
  const final = uniqueName(absDir, safe);
30260
- const abs = join23(absDir, final);
30261
- writeFileSync9(abs, data);
30262
- return { status: "ok", path: relative(root, abs).split(sep3).join("/"), name: final };
30379
+ const abs = join21(absDir, final);
30380
+ writeFileSync7(abs, data);
30381
+ return { status: "ok", path: relative2(root, abs).split(sep4).join("/"), name: final };
30263
30382
  }
30264
30383
  function createDocFolder(root, relDir, name) {
30265
30384
  const absDir = resolveDirPath(root, relDir);
30266
30385
  if (absDir === null) return { status: "no-dir" };
30267
30386
  try {
30268
- if (!statSync7(absDir).isDirectory()) return { status: "no-dir" };
30387
+ if (!statSync8(absDir).isDirectory()) return { status: "no-dir" };
30269
30388
  } catch {
30270
30389
  return { status: "no-dir" };
30271
30390
  }
30272
30391
  const safe = sanitizeUploadName(name);
30273
30392
  if (!safe) return { status: "bad-name" };
30274
- const abs = join23(absDir, safe);
30393
+ const abs = join21(absDir, safe);
30275
30394
  try {
30276
- statSync7(abs);
30395
+ statSync8(abs);
30277
30396
  return { status: "exists" };
30278
30397
  } catch {
30279
30398
  }
30280
- mkdirSync10(abs);
30281
- return { status: "ok", path: relative(root, abs).split(sep3).join("/"), name: safe };
30399
+ mkdirSync9(abs);
30400
+ return { status: "ok", path: relative2(root, abs).split(sep4).join("/"), name: safe };
30282
30401
  }
30283
30402
  function createDocFile(root, relDir, name, content) {
30284
30403
  const absDir = resolveDirPath(root, relDir);
30285
30404
  if (absDir === null) return { status: "no-dir" };
30286
30405
  try {
30287
- if (!statSync7(absDir).isDirectory()) return { status: "no-dir" };
30406
+ if (!statSync8(absDir).isDirectory()) return { status: "no-dir" };
30288
30407
  } catch {
30289
30408
  return { status: "no-dir" };
30290
30409
  }
@@ -30294,29 +30413,29 @@ function createDocFile(root, relDir, name, content) {
30294
30413
  if (!(ext in DOC_EXTENSIONS) && !(ext in CODE_EXTENSIONS)) return { status: "bad-name" };
30295
30414
  if (SKIP_FILES.has(safe)) return { status: "bad-name" };
30296
30415
  if (Buffer.byteLength(content, "utf8") > MAX_CONTENT_BYTES) return { status: "too-large" };
30297
- const abs = join23(absDir, safe);
30416
+ const abs = join21(absDir, safe);
30298
30417
  try {
30299
- writeFileSync9(abs, content, { encoding: "utf8", flag: "wx" });
30418
+ writeFileSync7(abs, content, { encoding: "utf8", flag: "wx" });
30300
30419
  } catch (err) {
30301
30420
  if (err.code === "EEXIST") return { status: "exists" };
30302
30421
  throw err;
30303
30422
  }
30304
- return { status: "ok", path: relative(root, abs).split(sep3).join("/"), name: safe };
30423
+ return { status: "ok", path: relative2(root, abs).split(sep4).join("/"), name: safe };
30305
30424
  }
30306
30425
  function moveDocEntry(root, from, to) {
30307
30426
  if (!from || !to || from.includes("\0") || to.includes("\0")) return { status: "not-found" };
30308
30427
  const absFrom = resolve7(root, from);
30309
- if (!absFrom.startsWith(root + sep3)) return { status: "not-found" };
30428
+ if (!absFrom.startsWith(root + sep4)) return { status: "not-found" };
30310
30429
  let stat;
30311
30430
  try {
30312
- stat = statSync7(absFrom);
30431
+ stat = statSync8(absFrom);
30313
30432
  } catch {
30314
30433
  return { status: "not-found" };
30315
30434
  }
30316
30435
  const isDir = stat.isDirectory();
30317
30436
  if (!isDir && !stat.isFile()) return { status: "not-found" };
30318
30437
  const absTo = resolve7(root, to);
30319
- if (!absTo.startsWith(root + sep3)) return { status: "bad-target" };
30438
+ if (!absTo.startsWith(root + sep4)) return { status: "bad-target" };
30320
30439
  const name = sanitizeUploadName(basename6(absTo));
30321
30440
  if (!name) return { status: "bad-target" };
30322
30441
  if (!isDir) {
@@ -30325,28 +30444,28 @@ function moveDocEntry(root, from, to) {
30325
30444
  return { status: "bad-target" };
30326
30445
  }
30327
30446
  }
30328
- const absToDir = dirname4(absTo);
30329
- if (resolveDirPath(root, relative(root, absToDir)) === null) return { status: "bad-target" };
30447
+ const absToDir = dirname3(absTo);
30448
+ if (resolveDirPath(root, relative2(root, absToDir)) === null) return { status: "bad-target" };
30330
30449
  try {
30331
- if (!statSync7(absToDir).isDirectory()) return { status: "bad-target" };
30450
+ if (!statSync8(absToDir).isDirectory()) return { status: "bad-target" };
30332
30451
  } catch {
30333
30452
  return { status: "bad-target" };
30334
30453
  }
30335
- const finalAbs = join23(absToDir, name);
30336
- if (isDir && (finalAbs === absFrom || finalAbs.startsWith(absFrom + sep3))) {
30454
+ const finalAbs = join21(absToDir, name);
30455
+ if (isDir && (finalAbs === absFrom || finalAbs.startsWith(absFrom + sep4))) {
30337
30456
  return { status: "into-self" };
30338
30457
  }
30339
30458
  try {
30340
- if (realpathSync(finalAbs) !== realpathSync(absFrom)) return { status: "exists" };
30459
+ if (realpathSync2(finalAbs) !== realpathSync2(absFrom)) return { status: "exists" };
30341
30460
  } catch {
30342
30461
  }
30343
30462
  renameSync3(absFrom, finalAbs);
30344
- return { status: "ok", path: relative(root, finalAbs).split(sep3).join("/"), name };
30463
+ return { status: "ok", path: relative2(root, finalAbs).split(sep4).join("/"), name };
30345
30464
  }
30346
30465
  function deleteDocEntry(root, path) {
30347
30466
  if (!path || path.includes("\0")) return { status: "not-found" };
30348
30467
  const abs = resolve7(root, path);
30349
- if (!abs.startsWith(root + sep3)) return { status: "not-found" };
30468
+ if (!abs.startsWith(root + sep4)) return { status: "not-found" };
30350
30469
  let stat;
30351
30470
  try {
30352
30471
  stat = lstatSync2(abs);
@@ -30355,10 +30474,10 @@ function deleteDocEntry(root, path) {
30355
30474
  }
30356
30475
  const isDir = stat.isDirectory();
30357
30476
  if (!isDir && !stat.isFile() && !stat.isSymbolicLink()) return { status: "not-found" };
30358
- rmSync12(abs, { recursive: isDir });
30477
+ rmSync10(abs, { recursive: isDir });
30359
30478
  return {
30360
30479
  status: "ok",
30361
- path: relative(root, abs).split(sep3).join("/"),
30480
+ path: relative2(root, abs).split(sep4).join("/"),
30362
30481
  type: isDir ? "dir" : "file"
30363
30482
  };
30364
30483
  }
@@ -30388,7 +30507,7 @@ function createDocsRouter({ gate = requireDocsAccess } = {}) {
30388
30507
  if (!resolved2) return c.json({ error: "not found" }, 404);
30389
30508
  let stat;
30390
30509
  try {
30391
- stat = statSync7(resolved2.abs);
30510
+ stat = statSync8(resolved2.abs);
30392
30511
  } catch {
30393
30512
  return c.json({ error: "not found" }, 404);
30394
30513
  }
@@ -30410,13 +30529,13 @@ function createDocsRouter({ gate = requireDocsAccess } = {}) {
30410
30529
  if (!abs) return c.json({ error: "not found" }, 404);
30411
30530
  let stat;
30412
30531
  try {
30413
- stat = statSync7(abs);
30532
+ stat = statSync8(abs);
30414
30533
  } catch {
30415
30534
  return c.json({ error: "not found" }, 404);
30416
30535
  }
30417
30536
  if (!stat.isFile()) return c.json({ error: "not found" }, 404);
30418
30537
  if (stat.size > MAX_RAW_BYTES) return c.json({ error: "file too large" }, 413);
30419
- return c.body(withDocLinkBridge(readFileSync19(abs, "utf8")), 200, {
30538
+ return c.body(withDocLinkBridge(readFileSync17(abs, "utf8")), 200, {
30420
30539
  "Content-Type": "text/html; charset=utf-8",
30421
30540
  "Content-Security-Policy": HTML_SHARE_CSP,
30422
30541
  "X-Content-Type-Options": "nosniff",
@@ -30534,7 +30653,7 @@ function createDocsRouter({ gate = requireDocsAccess } = {}) {
30534
30653
  if (!abs) return c.json({ error: "not found" }, 404);
30535
30654
  let stat;
30536
30655
  try {
30537
- stat = statSync7(abs);
30656
+ stat = statSync8(abs);
30538
30657
  } catch {
30539
30658
  return c.json({ error: "not found" }, 404);
30540
30659
  }
@@ -30583,7 +30702,7 @@ function createDocsRouter({ gate = requireDocsAccess } = {}) {
30583
30702
  if (!abs) return c.json({ error: "not found" }, 404);
30584
30703
  let stat;
30585
30704
  try {
30586
- stat = statSync7(abs);
30705
+ stat = statSync8(abs);
30587
30706
  } catch {
30588
30707
  return c.json({ error: "not found" }, 404);
30589
30708
  }
@@ -30601,7 +30720,7 @@ function createDocsRouter({ gate = requireDocsAccess } = {}) {
30601
30720
  title: kind ? extractTitle(abs, kind) : basename6(abs),
30602
30721
  mtime: stat.mtime.toISOString(),
30603
30722
  tooLarge: tooLarge || void 0,
30604
- content: tooLarge ? "" : readFileSync19(abs, "utf8")
30723
+ content: tooLarge ? "" : readFileSync17(abs, "utf8")
30605
30724
  });
30606
30725
  });
30607
30726
  app.put("/:id/docs/content", async (c) => {
@@ -30634,7 +30753,7 @@ function createDocsRouter({ gate = requireDocsAccess } = {}) {
30634
30753
  }
30635
30754
  let stat;
30636
30755
  try {
30637
- stat = statSync7(abs);
30756
+ stat = statSync8(abs);
30638
30757
  } catch {
30639
30758
  return { error: c.json({ error: "not found" }, 404) };
30640
30759
  }
@@ -30644,7 +30763,7 @@ function createDocsRouter({ gate = requireDocsAccess } = {}) {
30644
30763
  channel,
30645
30764
  rel,
30646
30765
  title: extractTitle(abs, "md"),
30647
- content: readFileSync19(abs, "utf8")
30766
+ content: readFileSync17(abs, "utf8")
30648
30767
  };
30649
30768
  };
30650
30769
  app.get("/:id/docs/translation/:lang", async (c) => {
@@ -30702,9 +30821,9 @@ function withDocLinkBridge(html) {
30702
30821
  var DOC_MENTION_RE = /(?<![\w@/`])@((?:[\w.-]+\/)+[\w.-]+\.[A-Za-z0-9]{1,6})(?::(\d+))?(?![\w-])/g;
30703
30822
  function isRealDoc(root, rel) {
30704
30823
  const abs = resolveDocPath(root, rel);
30705
- if (!abs || !existsSync22(abs)) return false;
30824
+ if (!abs || !existsSync21(abs)) return false;
30706
30825
  try {
30707
- return statSync8(abs).isFile();
30826
+ return statSync9(abs).isFile();
30708
30827
  } catch {
30709
30828
  return false;
30710
30829
  }
@@ -31143,7 +31262,7 @@ var BACKGROUND_CHECK_IN_MS = 30 * 6e4;
31143
31262
  var MISSED_MESSAGE_WINDOW_MS = 24 * 60 * 60 * 1e3;
31144
31263
  var MISSED_MESSAGE_THREAD_LIMIT = 100;
31145
31264
  var delay = (ms) => new Promise((r) => setTimeout(r, ms));
31146
- function stripPathPrefixes(label, roots, home = homedir8()) {
31265
+ function stripPathPrefixes(label, roots, home = homedir9()) {
31147
31266
  let out = label;
31148
31267
  for (const root of roots) {
31149
31268
  if (root) out = out.replaceAll(`${root.replace(/\/+$/, "")}/`, "");
@@ -32167,9 +32286,9 @@ ${msg.body}` : expandSkillCommand(channelConfig.claudeConfigDir, channelConfig.c
32167
32286
  }, activity: () => {
32168
32287
  } };
32169
32288
  }
32170
- let pending2 = ready;
32289
+ let pending = ready;
32171
32290
  const send = (event, payload, last = false) => {
32172
- pending2 = pending2.then(async (subscribed) => {
32291
+ pending = pending.then(async (subscribed) => {
32173
32292
  if (subscribed) {
32174
32293
  const res = await channel.send({ type: "broadcast", event, payload }).catch((err) => err.message);
32175
32294
  if (res !== "ok") {
@@ -32179,7 +32298,7 @@ ${msg.body}` : expandSkillCommand(channelConfig.claudeConfigDir, channelConfig.c
32179
32298
  return subscribed;
32180
32299
  }).catch(() => false);
32181
32300
  if (last) {
32182
- void pending2.finally(() => void this.supabase().removeChannel(channel));
32301
+ void pending.finally(() => void this.supabase().removeChannel(channel));
32183
32302
  }
32184
32303
  };
32185
32304
  return {
@@ -32226,9 +32345,9 @@ ${msg.body}` : expandSkillCommand(channelConfig.claudeConfigDir, channelConfig.c
32226
32345
  };
32227
32346
  return this.channelActivitySend;
32228
32347
  }
32229
- let pending2 = ready;
32348
+ let pending = ready;
32230
32349
  this.channelActivitySend = (event, payload) => {
32231
- pending2 = pending2.then(async (subscribed) => {
32350
+ pending = pending.then(async (subscribed) => {
32232
32351
  if (subscribed) {
32233
32352
  const res = await channel.send({ type: "broadcast", event, payload }).catch((err) => err.message);
32234
32353
  if (res !== "ok") {
@@ -34147,7 +34266,7 @@ ${matched.prompt}`,
34147
34266
 
34148
34267
  // src/store/automation-run-store.ts
34149
34268
  import Database3 from "better-sqlite3";
34150
- import { randomUUID as randomUUID4 } from "crypto";
34269
+ import { randomUUID as randomUUID3 } from "crypto";
34151
34270
  var LOG_RETENTION = 2e3;
34152
34271
  var AutomationRunStore = class {
34153
34272
  db;
@@ -34210,7 +34329,7 @@ var AutomationRunStore = class {
34210
34329
  if (ids.length === 0) return;
34211
34330
  const update = this.db.prepare("UPDATE automation_run_log SET row_uid = ? WHERE id = ?");
34212
34331
  this.db.transaction(() => {
34213
- for (const { id } of ids) update.run(randomUUID4(), id);
34332
+ for (const { id } of ids) update.run(randomUUID3(), id);
34214
34333
  })();
34215
34334
  }
34216
34335
  getLastRun(name) {
@@ -34255,7 +34374,7 @@ var AutomationRunStore = class {
34255
34374
  ).run(name, when.toISOString(), status);
34256
34375
  this.db.prepare(
34257
34376
  "INSERT INTO automation_run_log (row_uid, name, run_at, status, duration_ms) VALUES (?, ?, ?, ?, ?)"
34258
- ).run(randomUUID4(), name, when.toISOString(), status, durationMs ?? null);
34377
+ ).run(randomUUID3(), name, when.toISOString(), status, durationMs ?? null);
34259
34378
  const guard = this.holdUnsynced ? " AND synced_at IS NOT NULL" : "";
34260
34379
  this.db.prepare(
34261
34380
  `DELETE FROM automation_run_log
@@ -34528,18 +34647,18 @@ var ReactionStore = class {
34528
34647
  };
34529
34648
 
34530
34649
  // ../api/src/store/supabase-direct.ts
34531
- import { createClient as createClient2 } from "@supabase/supabase-js";
34532
- var REQUEST_TIMEOUT_MS3 = 15e3;
34650
+ import { createClient } from "@supabase/supabase-js";
34651
+ var REQUEST_TIMEOUT_MS2 = 15e3;
34533
34652
  function createDirectSupabaseClient() {
34534
34653
  const url = process.env["SUPABASE_URL"];
34535
34654
  const key = process.env["SUPABASE_SECRET_KEY"];
34536
34655
  if (!url || !key) {
34537
34656
  throw new Error("SUPABASE_URL / SUPABASE_SECRET_KEY not set \u2014 check .env");
34538
34657
  }
34539
- return createClient2(url, key, {
34658
+ return createClient(url, key, {
34540
34659
  auth: { persistSession: false },
34541
34660
  global: {
34542
- fetch: (input, init) => fetch(input, { ...init, signal: init?.signal ?? AbortSignal.timeout(REQUEST_TIMEOUT_MS3) })
34661
+ fetch: (input, init) => fetch(input, { ...init, signal: init?.signal ?? AbortSignal.timeout(REQUEST_TIMEOUT_MS2) })
34543
34662
  }
34544
34663
  });
34545
34664
  }
@@ -34639,12 +34758,12 @@ function startWatchdog(opts) {
34639
34758
  // src/index.ts
34640
34759
  var DRAIN_TIMEOUT_MS = 15e3;
34641
34760
  async function recoverStaleReactions(client, reactionStore) {
34642
- const pending2 = reactionStore.listAll();
34643
- if (pending2.length === 0) return;
34761
+ const pending = reactionStore.listAll();
34762
+ if (pending.length === 0) return;
34644
34763
  console.log(
34645
- `[${ts2()}] [flyspace] clearing ${pending2.length} stale reaction(s) from previous run`
34764
+ `[${ts2()}] [flyspace] clearing ${pending.length} stale reaction(s) from previous run`
34646
34765
  );
34647
- for (const r of pending2) {
34766
+ for (const r of pending) {
34648
34767
  try {
34649
34768
  await client.reactions.remove({
34650
34769
  channel: r.channelId,
@@ -34774,8 +34893,8 @@ async function startServer() {
34774
34893
  const shutdown = async (signal) => {
34775
34894
  if (shuttingDown) return;
34776
34895
  shuttingDown = true;
34777
- const pending2 = slackRuntime?.listeners.pendingCount() ?? 0;
34778
- console.log(`[${ts2()}] [flyspace] shutting down (${signal}, ${pending2} thread queue(s))`);
34896
+ const pending = slackRuntime?.listeners.pendingCount() ?? 0;
34897
+ console.log(`[${ts2()}] [flyspace] shutting down (${signal}, ${pending} thread queue(s))`);
34779
34898
  if (slackRuntime) {
34780
34899
  const drained = await slackRuntime.listeners.drain(DRAIN_TIMEOUT_MS);
34781
34900
  if (!drained) {
@@ -34815,15 +34934,35 @@ export {
34815
34934
  resolveUserId,
34816
34935
  ensureUsersCached,
34817
34936
  useLocalCache,
34818
- loadEnvFiles,
34819
- SLACK_ENV,
34820
- slackConfigured,
34821
- requireSlackBotToken,
34822
- loadConfig,
34937
+ isPermissionMode,
34938
+ isLogicalCwd,
34939
+ isUnderLogicalRoot,
34940
+ expandPath,
34941
+ canSeeChannel,
34942
+ refreshChannelRegistry,
34943
+ getChannelRegistry,
34944
+ getProfileChannelRegistry,
34945
+ findChannelById,
34946
+ findChannel,
34947
+ startChannelRegistryPolling,
34948
+ isCwdUsable,
34949
+ auditChannelCwds,
34950
+ warnOnBrokenChannelCwds,
34951
+ resolveCwd,
34952
+ ChannelCwdError,
34953
+ createChannel,
34954
+ DefaultChannelError,
34955
+ updateChannelById,
34956
+ markChannelGreeted,
34957
+ updateChannelsMcpConnections,
34958
+ ensureAgentDmChannel,
34959
+ ensureGeneralChannel,
34960
+ ensureMemberDmChannel,
34823
34961
  getWorkspaceDomain,
34824
34962
  insertWorkspaceDomain,
34825
34963
  updateWorkspaceDomainStatus,
34826
34964
  deleteWorkspaceDomain,
34965
+ allowedOrigins,
34827
34966
  crossOriginShell,
34828
34967
  corsForShell,
34829
34968
  createRequestSupabaseClient,
@@ -34877,6 +35016,7 @@ export {
34877
35016
  BRANDING_DEFAULTS,
34878
35017
  getWorkspaceBranding,
34879
35018
  upsertWorkspaceBranding,
35019
+ localDefaults,
34880
35020
  loadWorkspaceBranding,
34881
35021
  saveWorkspaceBranding,
34882
35022
  loadWorkspacePrompt,
@@ -34902,38 +35042,17 @@ export {
34902
35042
  clearClaudeAuthFailed,
34903
35043
  claudeAuthFailed,
34904
35044
  pinnedClaudeConfigDir,
35045
+ AGENT_AUTHOR,
35046
+ isHumanAuthor,
35047
+ deriveThreadTitle,
35048
+ syncPostToDashboard,
35049
+ resolveDashboardChannelId,
35050
+ postToDashboardChannel,
34905
35051
  refreshAutomationRegistry,
34906
35052
  startAutomationRegistryPolling,
34907
35053
  DEFAULT_TIMEZONE,
34908
35054
  loadAutomations,
34909
35055
  loadEffectiveAutomations,
34910
- DEFAULT_API_URL,
34911
- AuthApiError,
34912
- apiUrl,
34913
- deviceKeyPath,
34914
- credentialsPath,
34915
- ensureDeviceKey,
34916
- loadCredentials,
34917
- saveCredentials,
34918
- clearLocalAuth,
34919
- requestDeviceCode,
34920
- pollDeviceToken,
34921
- fetchWhoAmI,
34922
- boundWorkspaces,
34923
- revokeDevice,
34924
- getAccessToken,
34925
- acquireHostLock,
34926
- publishHostEndpoint,
34927
- readHostEndpoint,
34928
- setHostDbSender,
34929
- handleHostDbResult,
34930
- requestHostDb,
34931
- handleAttachmentUrlResult,
34932
- handlePluginSvgResult,
34933
- handleShouldRespondResult,
34934
- LOCAL_DB_PATH,
34935
- createHostDbClient,
34936
- useHostDbWithoutCredentials,
34937
35056
  runPersonaCmd,
34938
35057
  MEMORY_TYPES,
34939
35058
  isMemoryType,